﻿using System.Collections.Concurrent;
using System.Collections.Immutable;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO.Ports;
using System.Management;
using System.Reactive;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Threading;
using DynamicData;
using Microsoft.Extensions.DependencyInjection;
using Serilog;
using SimpleTool.ActivityUnit.EchoControl;
using SimpleTool.Server;
using SimpleTool.TransformComponent;
using static ICSharpCode.SharpZipLib.Zip.ExtendedUnixData;
using static OfficeOpenXml.ExcelErrorValue;

namespace SimpleTool.ActivityUnit
{
    public class ActivityDetetor
    {
        [Flags]
        enum FactoryType
        {
            Record = 2,
            State = 4,
            Value = 8
        }

        enum FailWhyinDisposeType //because and dispose type
        {
            Invalid,
            RegexpTool,
            ContentPopup,
            BitwiseTool
        }

        private static readonly ILogger Logger = Log.ForContext<ActivityDetetor>();

        //  产品和工序(acvitity - product and process)
        public (string, string) Actvt_PapPair = new();

        //  base data info
        private static class BSDT
        {
            public static string PRDFLAG = string.Empty;

            public static string IMEI = string.Empty;

            public static string SN = string.Empty;

            public static string DOID = string.Empty;

            public static string? QRCODE_1 = string.Empty;

            public static string? QRCODE_2 = string.Empty;

            public static List<string> QRCODE = [];

            public static void Init()
            {
                IMEI = string.Empty;
                SN = string.Empty;
                DOID = string.Empty;
            }
        }

        private sealed class CC_Blue : IDisposable
        {
            public Regex Regex = RegExp.RegExpBlueMatch();

            public string Port = string.Empty; //  保存蓝牙串口名

            public string Address = string.Empty; //  保存蓝牙地址

            public string? Signal = null; //  蓝牙信号值

            public Action<string> BlueOutput = (content) => { };

            public SerialPort BluetoothSerial = new() //  蓝牙串口
            {
                BaudRate = 115200,
                DataBits = 8,
                Parity = Parity.None,
                StopBits = StopBits.Two,
                Handshake = Handshake.None
            };

            public async void OutPut(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
            {
                if (BluetoothSerial.IsOpen)
                {
                    string content = BluetoothSerial.ReadExisting();
                    await Match(content);
                    BlueOutput.Invoke(content);
                }
            }

            public static string ReworkAddress(string blue)
            {
                string[] bluesplit = RegExp.RegExpBlueSeparator().Split(blue);
                if (bluesplit.Length > 6)
                {
                    return blue[3..];
                }
                else
                {
                    return blue;
                }
            }

            public async Task Match(string content, Action<string, string?>? infos = null)
            {
                await Task.Run(() =>
                {
                    var BlueMatch = Regex.Match(content);

                    if (BlueMatch.Groups.Count == 2)
                    {
                        Address = ReworkAddress(BlueMatch.Groups[1].Value);
                        infos?.Invoke(Address, null);
                    }
                    else if (BlueMatch.Groups.Count >= 3)
                    {
                        Address = ReworkAddress(BlueMatch.Groups[1].Value);
                        Signal = BlueMatch.Groups[2].Value;
                        infos?.Invoke(Address, Signal);
                    }
                });
            }

            public bool Open()
            {
                try
                {
                    if (!BluetoothSerial.IsOpen)
                    {
                        BluetoothSerial.Open();

                        if (BluetoothSerial.IsOpen)
                        {
                            BluetoothSerial.DataReceived += OutPut;
                            return true;
                        }
                        else
                        {
                            BluetoothSerial.DataReceived -= OutPut;
                            return false;
                        }
                    }
                    else
                    {
                        return true;
                    }
                }
                catch (Exception error)
                {
                    Logger.Print(RuntimeLog.LogType.Error, $"serial open error: {error.Message}, port: {BluetoothSerial.PortName}");
                    return false;
                }
            }

            public void Close(int type = 0)
            {
                switch (type)
                {
                    case 0:
                        if (BluetoothSerial.IsOpen)
                        {
                            BluetoothSerial.Close();
                        }
                        break;
                    case 1:
                        if (BluetoothSerial.IsOpen)
                        {
                            BluetoothSerial.Close();
                            BluetoothSerial.Dispose();
                        }
                        break;
                }
            }

            public bool Write(string command)
            {
                if (BluetoothSerial.IsOpen)
                {
                    Logger.Print(RuntimeLog.LogType.Error, "send blue command: ", command);
                    BluetoothSerial.Write(command + "\r\n");
                    return true;
                }
                else
                {
                    Logger.Print(RuntimeLog.LogType.Warning, "blue serial not open");
                    return false;
                }

            }

            public void Dispose()
            {
                GC.SuppressFinalize(this);
            }

            ~CC_Blue()
            {
                if (BluetoothSerial.IsOpen) BluetoothSerial.Close();
                BluetoothSerial.Dispose();
                BluetoothSerial.DataReceived -= OutPut;
            }
        }

        private sealed class Factory_Longterm
        {
            public string Lt_ExecptionAtrribute = string.Empty; //  报错节点中文名称

            public string Lt_CurrentApplyCommand = string.Empty; //  当前正在执行的指令

            public List<string> Lt_StatiSticalSteps = []; //  统计步骤

            public List<string> Lt_StatiSticalSubjoins = []; //  统计有效通过值

            public TestItemDeepSeatedSealed? Lt_CurrentApplyAttribute = null; //  保存当前节点信息

            public ConcurrentBag<FieldInfo> Lt_ValidFiedls = []; //  保存有效字段
        }

        private sealed class Factory_State
        {

            //  节点等待,此等待不存在超时情况
            public bool St_StepAwait = false;

            //  蓝牙串口名获取进入标识
            public bool St_Bluetooth_SerialPort_Get = false;

            //  蓝牙地址获取进入标识
            public bool St_Bluetooth_Address_Apply = false;

            //  蓝牙地址确认标识
            public bool St_Bluetooth_Address_Question = false;

            //  蓝牙代理等待标识
            public bool St_DelAwait_Reset_Watch = false;

            //  节点正则报错标识
            public bool St_StepRunning_Error = false;

            //  节点报错标识
            public bool St_ErrorFlag_Catch = false;

            //  最大重试次数标识
            public bool St_MaxTry_SoFar = false;

            //  是否直接执行，需要拼接的指令则等待拼接
            public bool St_DirectExecute = true;

            //  指令执行标识，某些指令在确认数据无效后需要跳过，避免设备数据污染
            public bool St_AllowableNext = true;

            //  准入条件校验，确认数据是否有效 - 写号
            public bool St_AllowableEntry = false;

            //  数据读取开关
            public bool St_DataStreamSwitch = false;

            //  是否允许打开蓝牙串口，该标志决定是否指定蓝牙串口号
            public bool St_IsBluetoothBoard = false;

            //  是否传承匹配值
            public bool St_IsHandDownValue = false;

            //  获取新流程至指令发送中间阶段，控制Run方法接收文本的状态，默认不获取，发送指令临近时打开状态，避免数据污染
            public bool St_ReceiveAdvanceFlag = false;

            public Dictionary<string, bool> OnceComditionMap = [];

        }

        private sealed class Factory_Record
        {
            public ConcurrentBag<string> Rc_SerialPortoutPut = []; //  收集串口输出

            public ConcurrentBag<string> Rc_ProcessValue = []; //  经过数据处理类型匹配的有效值

            public readonly ConcurrentDictionary<string, ConcurrentBag<string>> Rc_CachePassValue = []; //  保存通过值，当前优化为安全线程集合，避免出现多地访问截断流程的情况

            public ConcurrentBag<string> Rc_CollectedFields = []; //  保存通过字段

            public ConcurrentBag<FieldInfo> Rc_CanCheckFields = []; //  保存关键有效字段，对应 Rc_CollectedFields

            public CustomMessageBox.InquiryPopupInvoke? Rc_QuestioningReturn; //  保存弹框回执信息

            public List<string> Rc_FailInWhy = [string.Empty]; //  可能原因

            public List<(FailWhyinDisposeType, object?)> Rc_FailInWhyType = [(FailWhyinDisposeType.Invalid, null)]; //  可能原因辅助类型

            public string Rc_AlowableEntryType = "DB"; //  准入类型

            public (string, string, string, int)? Rc_DeviceFlag = null; //  缓存设备标识信息，从左到右依次为 产品名称 - 标识 - 工序名称 - 序号
        }

        private sealed class Factory_Value
        {
            public int MaxRetryCount = 2; //  最大重试次数

            public int CurRetryCount = 0; //  当前重试次数

            public int TimeoutMs = 7000; //  节点超时时间

            public string CurBluethAccording = string.Empty; //  蓝牙拼接字符

            public string CurAddtionAccording = string.Empty; //  指令拼接字符
        }

        private readonly IPowerPlantServer Server_Power;

        private readonly IActivityDetetorServer Server_Activity;

        private readonly IDataBaseServer Server_DB;

        private readonly DispatcherTimer ReuseOutTimer = new(); //  主动执行run方法，避免依赖串口推送

        private readonly CC_Blue ProductBlueCache = new();

        private readonly Factory_Longterm Prss_LongTerm = new();

        public readonly ConcurrentDictionary<string, string> ValidValueMaps = [];

        private readonly ConcurrentDictionary<string, Factory_State> Prss_State = new();

        private readonly ConcurrentDictionary<string, Factory_Record> Prss_Record = new();

        private readonly ConcurrentDictionary<string, Factory_Value> Prss_Value = new();

        private readonly MessageProPlant? MessagePro = null;

        //  当前流程
        private readonly ConcurrentStack<string> Safety_Step = new();

        //  流程状态
        private readonly ConcurrentStack<bool> Safety_Gate = new();

        //  测试节点名称
        private readonly ConcurrentStack<bool> Safety_Paddle = new();

        //  配置修改项
        private List<SupplementConfig> AtrributeSupplement = [];

        //  工序索引
        private int WorkIndex = 0;

        //  遗留值
        private static string? HandDownValue = null;

        //  是否长时间步骤，例如刷卡，程序已停止但是设备可能还在运行
        private bool isLongTimeAtrribute = false;

        public ActivityDetetor(MessageProPlant? messagePro = null)
        {
            App app = (App)Application.Current;
            Server_Power = app.ServiceProvider.GetRequiredService<IPowerPlantServer>();
            Server_Activity = app.ServiceProvider.GetRequiredService<IActivityDetetorServer>();
            Server_DB = app.ServiceProvider.GetRequiredService<IDataBaseServer>();
    
            ProductBlueCache.BlueOutput = (content) =>
            {
                if (Safety_Step.TryPeek(out string? Step) &&
                    ProductBlueCache.Signal is not null and string signal &&
                    Prss_Record.TryGetValue(Step, out Factory_Record? _Prss_Record))
                {

                    TryAdd(Prss_LongTerm.Lt_CurrentApplyCommand, signal);
                    _Prss_Record.Rc_SerialPortoutPut.Add(content);

                    if (signal.IsAbsoluteValidValue())
                    {
                        MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Message, $"蓝牙信号值: {signal}"));
                    }
                }
            };
            MessagePro = messagePro;
            ReuseOutTimer.Interval = TimeSpan.FromMicroseconds(3000);
            WeakEventManager<DispatcherTimer, EventArgs>.AddHandler(ReuseOutTimer, nameof(DispatcherTimer.Tick), (sender, e) => Run(string.Empty));
        }

        private void GetAssistAtrribute(TestItemDeepSeatedSealed process)
        {
            var Factory = FactoryWork(false, FactoryType.Record | FactoryType.Value | FactoryType.State);

            if (Factory is not null)
            {
                Factory_Record? _Prss_Record = Factory.Value.Item1;

                Factory_Value? _Prss_Value = Factory.Value.Item2;

                Factory_State? _Prss_State = Factory.Value.Item3;

                if (_Prss_Value != null)
                {
                    if (process.BluethAccording is not null and string _BluethAccording)
                    {
                        _Prss_Value.CurBluethAccording = _BluethAccording;
                    }
                    else
                    {
                        _Prss_Value.CurBluethAccording = ":";
                    }

                    if (process.AddtionAccording is not null and string _AddtionAccording)
                    {
                        _Prss_Value.CurAddtionAccording = _AddtionAccording;
                    }

                    if (process.TimeoutMs is not null and int _TimeoutMs)
                    {
                        _Prss_Value.TimeoutMs = _TimeoutMs;
                    }

                    if (process.MaxRetryCount is not null and int _MaxRetryCount)
                    {
                        _Prss_Value.MaxRetryCount = _MaxRetryCount; ;
                    }
                }

                if (_Prss_State != null)
                {
                    if (process.IsCombination is not null and bool _IsCombination)
                    {
                        _Prss_State.St_DirectExecute = !_IsCombination;
                    }

                    if (process.AllowableEntry is not null and bool _AllowableEntry)
                    {
                        _Prss_State.St_AllowableEntry = _AllowableEntry;
                    }

                    if (process.IsBluetoothBoard is not null and bool _IsBluetoothBoard)
                    {
                        _Prss_State.St_IsBluetoothBoard = _IsBluetoothBoard; ;
                    }

                    if (process.IsHandDownValue is not null and bool _IsHandDownValue)
                    {
                        _Prss_State.St_IsHandDownValue = _IsHandDownValue; ;
                    }
                }
                if (_Prss_Record != null)
                {
                    if (process.AllowableEntryType is not null and string _AllowableEntryType)
                    {
                        _Prss_Record.Rc_AlowableEntryType = _AllowableEntryType; ;
                    }
                }
                Logger.Print(RuntimeLog.LogType.Debug, "load assist attribute");
            }
        }

        public async Task ReadyRunning(List<TestItemDeepSeatedSealed> multilAtrributes)
        {
            if (ReuseOutTimer.IsEnabled) ReuseOutTimer.Stop();

            Stopwatch longTimeWatch = Stopwatch.StartNew();
            List<string> TestSteps = []; //  收集测试项
            bool isExeption = false; //  收集异常标识，当发生异常且当前步骤为耗时步骤时，做特殊处理

            MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Message, $"测试前准备中"));

            List<TestItemDeepSeatedSealed>? CloneValue = multilAtrributes.DeepCopy<List<TestItemDeepSeatedSealed>>();

            ImmutableList<TestItemDeepSeatedSealed>? DeepmultilAtrributes = [];

            if (CloneValue is not null) DeepmultilAtrributes = [.. CloneValue];

            foreach(TestItemDeepSeatedSealed process in DeepmultilAtrributes)
            {
                Parallel.ForEach(process.GetFields(1), (field) =>
                {
                    //  属性补充
                    if (AtrributeSupplement.Count > 0)
                    {
                        foreach (var supplement in AtrributeSupplement.Where(x => x.Step == process.Step))
                        {
                            string? ValidValue = field.GetValue(process)?.GetSafetyChar();

                            if (ValidValue is not null && ValidValue.Contains("DEF:"))
                            {
                                ValidValue = ValidValue.Replace("DEF:", "");
                                ValidValue = ValidValue.Replace("{" + $"{supplement.Name}" + "}", supplement.Value);
                                if (field.CanSafetyConvert(ValidValue, out object? CanUsevalue))
                                {
                                    field.SetValue(process, CanUsevalue);
                                }
                            }
                        }
                    }
                });
                if (process.AppendType is not null && process.AppendValue is not null)
                {
                    ValidValueMaps.AddOrUpdate(process.AppendType, process.AppendValue, (k, v) => process.AppendValue);
                }
            }

            ValidValueMaps.AddOrUpdate("DOID", BSDT.DOID, (k, v) => BSDT.DOID);
            ValidValueMaps.AddOrUpdate("IMEI", BSDT.IMEI, (k, v) => BSDT.IMEI);
            ValidValueMaps.AddOrUpdate("SN", BSDT.SN, (k, v) => BSDT.SN);
            ValidValueMaps.AddOrUpdate("BLUE", ProductBlueCache.Address, (k, v) => ProductBlueCache.Address);

            MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Message, $"开始测试..."));

            await Task.Run(async () =>
            {
                foreach (var process in DeepmultilAtrributes)
                {
                    if (!ReuseOutTimer.IsEnabled) ReuseOutTimer.Start(); //  初始化数据字典后再执行定时任务

                    Safety_Step.Push(process.Step); //  当前步骤名称
                    Safety_Paddle.Push(false); //  当前步骤状态
                    TestSteps.Add(process.Step); //  收集步骤名称

                    var Factory = FactoryWork(true, FactoryType.Value | FactoryType.State | FactoryType.Record); // 初始化缓存

                    if (Factory is not null)
                    {
                        string Step = Factory.Value.Item4;

                        Prss_LongTerm.Lt_ValidFiedls = [..process.GetFields(1)];
                        Prss_LongTerm.Lt_CurrentApplyAttribute = process;
                        Prss_LongTerm.Lt_CurrentApplyCommand = process.Command;
                        Prss_Record[Step].Rc_CanCheckFields = [.. Prss_LongTerm.Lt_ValidFiedls.Where(x => ActivityAssistBehivor.Behivor.AttributeCanCheckMap.Contains(x.Name))];

                        if (process.SendDelayMs is not null and int _SendDelayMs)
                        {
                            await Task.Delay(_SendDelayMs);
                        }
                        
                        else
                        {
                            await Task.Delay(300);
                        }
                        
                        GetAssistAtrribute(process);
                        
                        Prss_State[Step].St_ReceiveAdvanceFlag = true;

                        //  数据准入检查
                        if (Prss_State[Step].St_AllowableEntry) await DataAllowableEntry();

                        //  等待拼接。不直接执行
                        if (!Prss_State[Step].St_DirectExecute)
                        {
                            Logger.Print(RuntimeLog.LogType.Error, "--St_DirectExecute--1 ", Prss_State[Step].St_DirectExecute);
                            Stopwatch directWatch = Stopwatch.StartNew();
                            while (Safety_Gate.TryPeek(out bool _St_ProcessRunning) && _St_ProcessRunning)
                            {
                                if (directWatch.ElapsedMilliseconds > Prss_Value[Step].TimeoutMs)
                                {
                                    MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Message, $"指令拼接超时"));
                                    break;
                                }
                                if (Prss_State[Step].St_DirectExecute)
                                {
                                    break;
                                }
                                await Task.Delay(100);
                            }
                        }

                        //  上一次长时间流程失败后则增加等待，避免产测执行后设备流程未结束得情况
                        if (isLongTimeAtrribute)
                        {
                            int waitTime = 1;
                            MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Message,
                                        $"上一个耗时流程可能未结束，等待中，稍后进行操作"));
                            while (Safety_Gate.TryPeek(out bool _Gate) && _Gate)
                            {
                                MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Message, $"等待 {waitTime} 秒"));
                                if (longTimeWatch.ElapsedMilliseconds > 7000)
                                {
                                    isLongTimeAtrribute = false;
                                    break;
                                }
                                waitTime++;
                                await Task.Delay(1000);
                            }
                        }

                        //  此状态决定指令是否执行，例如写号时，工单数据已使用时就不必再执行指令覆盖了，会导致破坏原数据一致性
                        //  Safety_Gate 状态为true时才执行，例如准入不通过时，不再执行该条件下的代码
                        if (Prss_State[Step].St_AllowableNext && Safety_Gate.TryPeek(out bool EntryCheck) && EntryCheck)
                        {
                            Logger.Print(RuntimeLog.LogType.Debug, "execute prepare command: ", Prss_LongTerm.Lt_CurrentApplyCommand.Trim());

                            if (ExecuteCommand())
                            {
                                MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Message, $"正在进行: {Step}, 请注意是否需要手动操作，执行指令: {Prss_LongTerm.Lt_CurrentApplyCommand}"));

                                MessagePro?.Invoke(new FlyingDove(MessageProPlantType.HeartBeats, $"结束测试"));

                                //  以 St_ProcessRunning1 为依据，控制结果输出
                                Stopwatch TimeoutMswatch = Stopwatch.StartNew();
                                while (Safety_Gate.TryPeek(out bool _Gate) && _Gate)
                                {
                                    if (Safety_Paddle.TryPeek(out bool St_StepRunning) && St_StepRunning)
                                    {
                                        MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Message | MessageProPlantType.Success, $"{Step}->测试通过", WorkIndex));
                                        Prss_LongTerm.Lt_StatiSticalSteps.Add($"{Step}: 通过");
                                        if (Prss_Record[Step].Rc_CachePassValue.TryGetValue(process.Command, out ConcurrentBag<string>? _passValues))
                                        {
                                            Prss_LongTerm.Lt_StatiSticalSubjoins.Add($"{Step}:{_passValues.Join(",")}");
                                        }
                                        WorkIndex++;
                                        break;
                                    }

                                    if (Prss_State[Step].St_DelAwait_Reset_Watch)
                                    {
                                        TimeoutMswatch = Stopwatch.StartNew();
                                        Prss_State[Step].St_StepAwait = false;
                                        Prss_State[Step].St_DelAwait_Reset_Watch = false;
                                        MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Message, $"重置计时状态，删除等待"));
                                    }

                                    if (TimeoutMswatch.ElapsedMilliseconds > Prss_Value[Step].TimeoutMs && !Prss_State[Step].St_StepAwait)
                                    {
                                        if (St_StepRunning)
                                        {
                                            MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Message | MessageProPlantType.Success,
                                                $"{Step}->重发测试通过", WorkIndex));
                                            continue;
                                        }
                                        else
                                        {
                                            if (Prss_Value[Step].MaxRetryCount > Prss_Value[Step].CurRetryCount)
                                            {
                                                TimeoutMswatch = Stopwatch.StartNew();

                                                await RetryProcess();
                                            }
                                            else
                                            {
                                                DoTestFail();

                                                DoPossibleCauseType();

                                                //  手机测试信息作为统计数据
                                                Prss_LongTerm.Lt_StatiSticalSteps.Add($"{Step}: 不通过");
                                                if (Prss_Record[Step].Rc_CachePassValue.TryGetValue(process.Command, out ConcurrentBag<string>? _passValues))
                                                {
                                                    Prss_LongTerm.Lt_StatiSticalSubjoins.Add($"{Step}:{_passValues.Join(",")}");
                                                }
                                                else
                                                {
                                                    Prss_LongTerm.Lt_StatiSticalSubjoins.Add($"{Step}:");
                                                }

                                                isExeption = true;

                                                await FlagVerify();

                                                TestResultRegister _TestResultRegister = new()
                                                {
                                                    Product = Actvt_PapPair.Item1,
                                                    Process = Actvt_PapPair.Item2,
                                                    Step = Prss_LongTerm.Lt_StatiSticalSteps.Join("&&"),
                                                    Subjoin = Prss_LongTerm.Lt_StatiSticalSubjoins.Join("&&"),
                                                    Origin = Prss_LongTerm.Lt_ExecptionAtrribute,
                                                    Imei = BSDT.IMEI,
                                                    Result = !isExeption,
                                                };

                                                MessagePro?.Invoke(new FlyingDove(MessageProPlantType.ResultRegister, _TestResultRegister));
                                                
                                                Safety_Gate.Push(false);
                                                break;
                                            }
                                        }
                                    }
                                    await Task.Delay(200);
                                }
                            }
                            else
                            {
                                TaskRelease(isExeption);
                                break;
                            }
                        }
                        else if (!Prss_State[Step].St_AllowableNext) //  跳过指令执行
                        {
                            MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Message | MessageProPlantType.Success, $"{Step}->测试通过", WorkIndex));
                            WorkIndex++;
                        }

                        if (Safety_Gate.TryPeek(out bool St_ProcessRunning) && !St_ProcessRunning)
                        {
                            MessagePro?.Invoke(new FlyingDove(MessageProPlantType.HeartBeats, "开始测试"));
                            MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Message, "进程已停止"));
                            TaskRelease(isExeption);
                            break;
                        }

                        if (WorkIndex == multilAtrributes.Count)
                        {
                            MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Message, "当前工序测试完成，进程已停止"));
                            MessagePro?.Invoke(new FlyingDove(MessageProPlantType.PushFinish, new ActivityDetetorSuccess
                            {
                                TestSteps = TestSteps.Select(x => $"({x}=OK)").Join(""),
                                IMEI = BSDT.IMEI
                            }));
                            MessagePro?.Invoke(new FlyingDove(MessageProPlantType.HeartBeats, "开始测试"));

                            if (!string.IsNullOrEmpty(Actvt_PapPair.Item1) && !string.IsNullOrEmpty(Actvt_PapPair.Item2))
                            {
                                TestResultRegister _TestResultRegister = new()
                                {
                                    Product = Actvt_PapPair.Item1,
                                    Process = Actvt_PapPair.Item2,
                                    Step = Prss_LongTerm.Lt_StatiSticalSteps.Join("&&"),
                                    Subjoin = Prss_LongTerm.Lt_StatiSticalSubjoins.Join("&&"),
                                    Origin = string.Empty,
                                    Imei = BSDT.IMEI,
                                    Result = !isExeption
                                };

                                if (Prss_Record[Step].Rc_CachePassValue.TryGetValue(process.Command, out ConcurrentBag<string>? passs))
                                {
                                    _TestResultRegister.Subjoin = passs.Join("、");
                                }
                                MessagePro?.Invoke(new FlyingDove(MessageProPlantType.ResultRegister, _TestResultRegister));
                            }
                            TaskRelease(isExeption);
                        }
                    }
                }
            });
        }

        public async void Run(string content)
        {
            var Factory = FactoryWork(false, FactoryType.Record | FactoryType.State);

            if (Factory is not null &&
                Factory.Value.Item1 is not null &&
                Factory.Value.Item3 is not null &&
                Safety_Gate.TryPeek(out bool St_ProcessRunning) && St_ProcessRunning)
            {
                Factory_Record _Prss_Record = Factory.Value.Item1;

                Factory_State _Prss_State = Factory.Value.Item3;

                string Step = Factory.Value.Item4;

                if (_Prss_State.St_ReceiveAdvanceFlag)
                {
                    if (!_Prss_Record.Rc_SerialPortoutPut.Contains(content)) _Prss_Record.Rc_SerialPortoutPut.Add(content);
                    try
                    {
                        if (Prss_LongTerm.Lt_CurrentApplyAttribute is not null)
                        {
                            for (int index = 0; index < _Prss_Record.Rc_SerialPortoutPut.Count; index++) 
                            {
                                string _content = _Prss_Record.Rc_SerialPortoutPut.ElementAt(index);
                            
                                foreach (var Field in Prss_LongTerm.Lt_ValidFiedls)
                                {
                                    if (Field.GetValue(Prss_LongTerm.Lt_CurrentApplyAttribute) is not null and object Value)
                                    {
                                        string ValidValue = Value.GetSafetyChar();

                                        switch (Field.Name)
                                        {
                                            case nameof(TestItemDeepSeatedSealed.PassFlag):

                                                List<string> keyword = [.. RegExp.RegExpMultiSpacing().Split(ValidValue)];
                                                if (!_Prss_Record.Rc_CollectedFields.Contains(Field.Name))
                                                {
                                                    int contain = 0;
                                                    foreach (var expect in keyword)
                                                    {
                                                        if (_Prss_Record.Rc_SerialPortoutPut.Any(x => x.Contains(expect))) contain++;
                                                    }

                                                    if (contain == keyword.Count)
                                                    {
                                                        _Prss_Record.Rc_CollectedFields.Add(Field.Name);
                                                        _Prss_Record.Rc_FailInWhy = [string.Empty];
                                                        _Prss_Record.Rc_FailInWhyType = [(FailWhyinDisposeType.Invalid, null)];
                                                        MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Message, $"匹配到通过标志: {keyword.Join("-")}"));
                                                    }
                                                    else
                                                    {
                                                        _Prss_Record.Rc_FailInWhy = ["没有匹配到通过标识，点击该文本以确认原始输出是否包含通过标识"];

                                                        _Prss_Record.Rc_FailInWhyType = [(FailWhyinDisposeType.ContentPopup, null)];
                                                    }
                                                }
                                                break;

                                            case nameof(TestItemDeepSeatedSealed.PassMatch):

                                                if (!_Prss_Record.Rc_CollectedFields.Contains(Field.Name))
                                                {
                                                    string value = string.Empty;


                                                    Match match = Regex.Match(_content, ValidValue.GetSafetyChar(true));
                                                    if (match.Groups.Count >= 2)
                                                    {
                                                        value = Regex.Match(_content, ValidValue.GetSafetyChar(true)).Groups[1].Value;
                                                    }
                                                    else
                                                    {
                                                        value = Regex.Match(_content, ValidValue.GetSafetyChar(true)).Groups[0].Value;
                                                    }

                                                    if (!string.IsNullOrEmpty(value))
                                                    {

                                                        value = value.Trim();
                                                        if (_Prss_State.St_IsHandDownValue) HandDownValue = value; //  传承值
                                                        TryAdd(Prss_LongTerm.Lt_CurrentApplyCommand, value);
                                                        _Prss_Record.Rc_FailInWhy = [string.Empty];
                                                        _Prss_Record.Rc_FailInWhyType = [(FailWhyinDisposeType.Invalid, null)];
                                                        _Prss_Record.Rc_CollectedFields.Add(Field.Name);
                                                        MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Message, $"匹配到通过值: {value}"));
                                                    }
                                                    else
                                                    {
                                                        _Prss_Record.Rc_FailInWhy = ["可能正则存在错误，当前已保留串口输出,是否需要正则调试,需要调试则点击该文本"];

                                                        _Prss_Record.Rc_FailInWhyType = [(FailWhyinDisposeType.RegexpTool, ValidValue.GetSafetyChar(true))];
                                                    }
                                                }
                                                break;

                                            case nameof(TestItemDeepSeatedSealed.PassValueVirify):

                                                if (!_Prss_Record.Rc_CollectedFields.Contains(Field.Name))
                                                {
                                                    if (_Prss_Record.Rc_CachePassValue.TryGetValue(Prss_LongTerm.Lt_CurrentApplyCommand, out ConcurrentBag<string>? passsValue))
                                                    {
                                                        int indexof = passsValue.IndexOf(ValidValue.Trim());
                                                        if (indexof != -1)
                                                        {
                                                            _Prss_Record.Rc_CollectedFields.Add(Field.Name);
                                                        }
                                                        else
                                                        {
                                                            if (!_Prss_Record.Rc_CollectedFields.Contains(nameof(TestItemDeepSeatedSealed.PassMatch)))
                                                            {
                                                                _Prss_Record.Rc_FailInWhy = ["请检查是否正确设置了通过值匹配，当前匹配不通过"];
                                                            }
                                                            else
                                                            {
                                                                _Prss_Record.Rc_FailInWhy = [$"当前:{passsValue.ElementAt(indexof)} - 预期:{Value}，当前匹配不通过"];
                                                            }

                                                            string hint = $"是否设置通过值匹配: {Prss_LongTerm.Lt_CurrentApplyAttribute?.PassMatch is not null}\r\n" +
                                                                          $"数据处理类型: {Prss_LongTerm.Lt_CurrentApplyAttribute?.ValueProcessingType}\r\n" +
                                                                          $"预期校验的的值: {ValidValue}，已保存串口输出，可点击此处打开正则工具进行调试\r\n";

                                                            _Prss_Record.Rc_FailInWhyType = [(FailWhyinDisposeType.RegexpTool, hint)];
                                                        }
                                                    }
                                                }
                                                break;

                                            case nameof(TestItemDeepSeatedSealed.ErrorFlag):

                                                if (!string.IsNullOrEmpty(ValidValue) && !_Prss_State.St_ErrorFlag_Catch)
                                                {
                                                    string[] Error_Values = RegExp.RegExpMultiSpacing().Split(ValidValue);

                                                    foreach (var error in Error_Values)
                                                    {
                                                        if (_content.Contains(error))
                                                        {
                                                            _Prss_State.St_ErrorFlag_Catch = true;
                                                            MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Message, $"匹配到了一个错误值{error},继续尝试执行流程"));
                                                            break;
                                                        }
                                                    }
                                                }
                                                break;

                                            case nameof(TestItemDeepSeatedSealed.AppendValue):

                                                if (!_Prss_Record.Rc_CollectedFields.Contains(Field.Name) &&
                                                    (!_Prss_State.OnceComditionMap.ContainsKey(Field.Name) ||
                                                     (_Prss_State.OnceComditionMap.TryGetValue(Field.Name, out bool _AppendValue) && !_AppendValue)))
                                                {
                                                    _Prss_State.OnceComditionMap[Field.Name] = true;

                                                    _Prss_Record.Rc_CollectedFields.Add(Field.Name);

                                                    await CommandAppend(ValidValue);

                                                }
                                                break;

                                            case nameof(TestItemDeepSeatedSealed.MaxContentLength):
                                                if (!_Prss_Record.Rc_CollectedFields.Contains(Field.Name))
                                                {
                                                    int totalindex = _Prss_Record.Rc_ProcessValue.Count;
                                                    int countindex = 0;
                                                    foreach (var pass in _Prss_Record.Rc_ProcessValue)
                                                    {
                                                        if (int.TryParse(ValidValue, out int length))
                                                        {
                                                            if (pass.Length == length)
                                                            {
                                                                countindex++;
                                                                MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Message, $"字符长度匹配: 当前 {pass.Length} 预期{length}， 匹配通过"));
                                                            }
                                                        }
                                                        else
                                                        {
                                                            _Prss_Record.Rc_FailInWhy = ["请检查是否设置了通过值匹配，因为没有获取到上一个值"];
                                                        }

                                                    }
                                                    if (totalindex == countindex) _Prss_Record.Rc_CollectedFields.Add(Field.Name);
                                                }
                                                break;

                                            case nameof(TestItemDeepSeatedSealed.ValidValueRange):

                                                if (!_Prss_Record.Rc_CollectedFields.Contains(Field.Name))
                                                {
                                                    List<string> splits = [.. RegExp.RegExpMultiSpacing().Split(ValidValue)];
                                                    if (splits.Count >= 2)
                                                    {
                                                        if (int.TryParse(splits[0].Trim(), out int min) && int.TryParse(splits[1].Trim(), out int max))
                                                        {
                                                            int totalindex = _Prss_Record.Rc_ProcessValue.Count;

                                                            bool FailWhyState = false;

                                                            if (totalindex > 0)
                                                            {
                                                                int coutindex = 0;
                                                                foreach (var processing in _Prss_Record.Rc_ProcessValue)
                                                                {
                                                                    if (int.TryParse(processing.Trim(), out int processValue))
                                                                    {
                                                                        if (min <= processValue && processValue <= max)
                                                                        {

                                                                            MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Message, $"有效区间值校验: {min} {processValue} {max}"));
                                                                            coutindex++;
                                                                        }
                                                                        else
                                                                        {
                                                                            _Prss_Record.Rc_FailInWhy = [$"有效值不符合预期, 值: {processValue}, 区间: {min}-{max}"];
                                                                        }
                                                                    }
                                                                    else
                                                                    {
                                                                        string hint = $"是否设置通过值匹配: {Prss_LongTerm.Lt_CurrentApplyAttribute?.PassMatch is not null}\r\n" +
                                                                                      $"数据处理类型: {Prss_LongTerm.Lt_CurrentApplyAttribute?.ValueProcessingType}\r\n" +
                                                                                      $"解析失败的值: {processing} \r\n" +
                                                                                      $"当前区间: {ValidValue}";

                                                                        _Prss_Record.Rc_FailInWhy = ["有效值提取有误，请检查是否设置了数据处理类型 或者 是否设置了通过值匹配,点击此查看详情"];
                                                                        _Prss_Record.Rc_FailInWhyType = [(FailWhyinDisposeType.ContentPopup, hint)];
                                                                        FailWhyState = true;

                                                                    }
                                                                }
                                                                if (coutindex == totalindex)
                                                                {
                                                                    _Prss_Record.Rc_CollectedFields.Add(Field.Name);
                                                                }
                                                                else
                                                                {
                                                                    if (!FailWhyState)
                                                                    {
                                                                        string hint = $"是否设置通过值匹配: {Prss_LongTerm.Lt_CurrentApplyAttribute?.PassMatch is not null}\r\n" +
                                                                                      $"数据处理类型: {Prss_LongTerm.Lt_CurrentApplyAttribute?.ValueProcessingType}\r\n" +
                                                                                      $"通过值: {_Prss_Record.Rc_ProcessValue.Join("、")}\r\n" +
                                                                                      $"当前区间: {ValidValue}";

                                                                        _Prss_Record.Rc_FailInWhy = ["有效值提取有误，请检查是否设置了数据处理类型 或者 是否设置了通过值匹配,点击此查看详情"];
                                                                        _Prss_Record.Rc_FailInWhyType = [(FailWhyinDisposeType.ContentPopup, hint)];
                                                                    }
                                                                }
                                                            }
                                                        }
                                                        else
                                                        {
                                                            _Prss_Record.Rc_FailInWhy = ["请检查区间数据类型输入是否有误,点击此处查看"];
                                                            _Prss_Record.Rc_FailInWhyType = [(FailWhyinDisposeType.ContentPopup, ValidValue)];
                                                        }
                                                    }
                                                    else
                                                    {
                                                        _Prss_Record.Rc_FailInWhy = ["请检查区间格式设置是否有误,点击此处查看"];
                                                        _Prss_Record.Rc_FailInWhyType = [(FailWhyinDisposeType.ContentPopup, ValidValue)];
                                                    }
                                                }
                                                break;

                                            case nameof(TestItemDeepSeatedSealed.ValueProcessingType):

                                                if (_Prss_Record.Rc_CachePassValue.TryGetValue(Prss_LongTerm.Lt_CurrentApplyCommand, out ConcurrentBag<string>? Passalues))
                                                {
                                                    foreach (var pass in Passalues)
                                                    {
                                                        string left = string.Empty;
                                                        string right = string.Empty;
                                                        List<string> splits = [.. RegExp.RegExpMultiSpacing().Split(pass)];
                                                        if (splits.Count >= 2)
                                                        {
                                                            left = splits[0].Trim();
                                                            right = splits[1].Trim();
                                                        }

                                                        switch (ValidValue)
                                                        {
                                                            case "左值":
                                                                if (!string.IsNullOrEmpty(left) && !_Prss_Record.Rc_ProcessValue.Contains(left))
                                                                {
                                                                    _Prss_Record.Rc_ProcessValue.Add(left);
                                                                }
                                                                break;

                                                            case "右值":
                                                                if (!string.IsNullOrEmpty(right) && !_Prss_Record.Rc_ProcessValue.Contains(right))
                                                                {
                                                                    _Prss_Record.Rc_ProcessValue.Add(right);
                                                                }
                                                                break;

                                                            case "蓝牙":

                                                            case "整值":
                                                                if (!string.IsNullOrEmpty(pass.Trim()) && !_Prss_Record.Rc_ProcessValue.Contains(pass.Trim()))
                                                                {
                                                                    _Prss_Record.Rc_ProcessValue.Add(pass.Trim());
                                                                }
                                                                break;

                                                            case "标识":
                                                                if (_Prss_Record.Rc_CachePassValue.TryGetValue(
                                                                    Prss_LongTerm.Lt_CurrentApplyCommand, out ConcurrentBag<string>? _passValues) && !Passalues.IsEmpty &&
                                                                    (!_Prss_State.OnceComditionMap.ContainsKey("_DisposeFlag") ||
                                                                    (_Prss_State.OnceComditionMap.TryGetValue("_DisposeFlag", out bool _DisposeFlag) && !_DisposeFlag)))
                                                                {
                                                                    _Prss_State.OnceComditionMap["_DisposeFlag"] = true;

                                                                    _ = FlagVerify(true, (Flags) =>
                                                                    {
                                                                        if (Flags.Count == 0)
                                                                        {
                                                                            MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Message | MessageProPlantType.Failed, $"{Step}->测试不通过", WorkIndex));
                                                                            _ = FlagVerify();
                                                                        }
                                                                        else
                                                                        {
                                                                            TryAdd(Prss_LongTerm.Lt_CurrentApplyCommand, Flags);
                                                                        }
                                                                    });
                                                                }
                                                                break;
                                                        }
                                                    }
                                                }
                                                break;

                                            case nameof(TestItemDeepSeatedSealed.IsLinkedToPrevious):
                                                if (!_Prss_Record.Rc_CollectedFields.Contains(Field.Name) &&
                                                    Prss_LongTerm.Lt_CurrentApplyAttribute is not null)
                                                {
                                                    if (_Prss_Record.Rc_CachePassValue.TryGetValue(Prss_LongTerm.Lt_CurrentApplyAttribute.Command, out ConcurrentBag<string>? passValue))
                                                    {
                                                        if (HandDownValue is not null) passValue.Add(HandDownValue);

                                                        int CanPassCount = passValue.Count(x => x == HandDownValue);

                                                        if (CanPassCount >= 2)
                                                        {

                                                            string values = passValue.Join(" - ");
                                                            _Prss_Record.Rc_CollectedFields.Add(Field.Name);
                                                            MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Message, $"前后值: {values}"));
                                                        }
                                                        else
                                                        {
                                                            if (passValue.IsEmpty)
                                                            {
                                                                _Prss_Record.Rc_FailInWhy = ["请检查是否设置了通过值匹配，因为没有获取到上一个值"];
                                                            }
                                                            else
                                                            {
                                                                string hint = $"当前的通过值: {passValue.Join("、")}\r\n" +
                                                                              $"流传的通过值: {HandDownValue}\r\n" +
                                                                              $"匹配成功的次数: {CanPassCount}";

                                                                _Prss_Record.Rc_FailInWhy = ["关联上一个值失败了，点击此处查看详情"];

                                                                _Prss_Record.Rc_FailInWhyType = [(FailWhyinDisposeType.ContentPopup, ValidValue.GetSafetyChar(true))];

                                                            }
                                                        }
                                                    }
                                                }
                                                break;

                                            case nameof(TestItemDeepSeatedSealed.ContainAtthis):

                                                if (!_Prss_Record.Rc_CollectedFields.Contains(Field.Name) && 
                                                    !_Prss_State.OnceComditionMap.ContainsKey(nameof(TestItemDeepSeatedSealed.ContainAtthis)))
                                                {
                                                    string containValue = ValidValue.ToUpper();

                                                    List<string> containValues = [.. RegExp.RegExpMultiSpacing().Split(containValue).Select(x => x.Trim())];

                                                    int containPass = 0; //  通过项统计

                                                    bool IsXorVerify = false; //  是否开启Xor位异或校验

                                                    if (Prss_LongTerm.Lt_CurrentApplyAttribute?.IsXorVerify is not null and bool _IsXorVerify && _IsXorVerify) IsXorVerify = _IsXorVerify;

                                                    // -1 空的  0 通过 1 位异或 + 包含通过 2 位异或不一致
                                                    foreach (var contain in containValues)
                                                    {
                                                        ContainAtrribute(contain, _content, (result) =>
                                                        {
                                                            switch (result)
                                                            {
                                                                case -1:
                                                                    MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Question, new CustomMessageBox.InquiryPopupField()
                                                                    {
                                                                        title = "参数为空",
                                                                        type = 1,
                                                                        message = "请进入参数设置界面选择或输入参数",
                                                                        options = ["知道了"]
                                                                    }));
                                                                    Safety_Paddle.Push(false);
                                                                    return;
                                                                case 0:
                                                                    break;
                                                                case 1:
                                                                    containPass++;
                                                                    break;
                                                                case 2:
                                                                    Safety_Paddle.Push(false);
                                                                    return;
                                                            }
                                                        }, IsXorVerify);
                                                    }

                                                    if (containPass == containValues.Count)
                                                    {
                                                        _Prss_State.OnceComditionMap[nameof(TestItemDeepSeatedSealed.ContainAtthis)] = true;
                                                        _Prss_Record.Rc_CollectedFields.Add(Field.Name);
                                                    }
                                                }
                                                break;

                                            case nameof(TestItemDeepSeatedSealed.WriteDBdataUseTraces):
                                                if (!_Prss_Record.Rc_CollectedFields.Contains(Field.Name))
                                                {
                                                    _Prss_Record.Rc_CollectedFields.Add(Field.Name);

                                                    switch (ValidValue)
                                                    {
                                                        case "读":
                                                            await WriteDBUseTraces(BSDT.IMEI, 1, () =>
                                                            {
                                                                MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Message, $"{BSDT.IMEI} 完成数据库校号记录写入"));
                                                            }, 
                                                            (error) =>
                                                            {
                                                                _Prss_Record.Rc_FailInWhy = ["数据库读取记录时间更新失败，点击此文本查看报错提示"];

                                                                _Prss_Record.Rc_FailInWhyType = [(FailWhyinDisposeType.ContentPopup, error)];
                                                            });
                                                            break;

                                                        case "写":
                                                            await WriteDBUseTraces(BSDT.IMEI, 0, () =>
                                                            {
                                                                MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Message, $"{BSDT.IMEI} 完成数据库写号记录写入"));
                                                            },
                                                            (error) =>
                                                            {
                                                                _Prss_Record.Rc_FailInWhy = ["数据库写号记录时间更新失败，点击此文本查看报错提示"];

                                                                _Prss_Record.Rc_FailInWhyType = [(FailWhyinDisposeType.ContentPopup, error)];
                                                            });
                                                            break;
                                                    }
                                                }
                                                break;

                                            case nameof(TestItemDeepSeatedSealed.IsAccessOneNet):

                                                if (!_Prss_Record.Rc_CollectedFields.Contains(Field.Name))
                                                {
                                                    if (Prss_LongTerm.Lt_CurrentApplyAttribute?.OneNetUrl is not null and string _Url &&
                                                        Prss_LongTerm.Lt_CurrentApplyAttribute.OneNetProductID is not null and string _ID &&
                                                        !_Prss_State.OnceComditionMap.ContainsKey(Field.Name))
                                                    {
                                                        _Prss_State.OnceComditionMap[Field.Name] = true;

                                                        OneNetAccessServer server = new();

                                                        OneNetAccessServer.Response? response = await server.Access(_Url, _ID, BSDT.IMEI);

                                                        Logger.Print(RuntimeLog.LogType.Debug, $"onenet base request info-> url:{_Url} id:{_ID} IMEI:{BSDT.IMEI}");

                                                        if (response is not null)
                                                        {
                                                            if (response.code == 0)
                                                            {
                                                                _Prss_Record.Rc_CollectedFields.Add(Field.Name);
                                                                MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Message, $"OneNet访问成功"));
                                                            }
                                                            else
                                                            {
                                                                MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Message, $"OneNet访问失败 {response.code}{response.msg}"));
                                                            }
                                                        }
                                                        else
                                                        {
                                                            MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Message, $"OneNet访问无应答"));
                                                        }
                                                    }
                                                }
                                                break;

                                            case nameof(TestItemDeepSeatedSealed.AllowableString):
                                                string[] filterchars = RegExp.RegExpMultiSpacing().Split(ValidValue);

                                                foreach(var f in filterchars)
                                                {
                                                    string stdinKey = _content + "&" + index;

                                                    if (_content.Contains(f) && 
                                                        !_Prss_State.OnceComditionMap.ContainsKey(stdinKey))
                                                    {
                                                        _Prss_State.OnceComditionMap.Add(stdinKey, true);
                                                        MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Message, _content));
                                                    }
                                                }
                                                break;
                                        }
                                    }
                                }

                                List<string> CanCheckItems = [.. _Prss_Record.Rc_CanCheckFields.Select(i => i.Name)];

                                if (CanCheckItems.Count == _Prss_Record.Rc_CollectedFields.Count &&
                                    CanCheckItems.All(_value => _Prss_Record.Rc_CollectedFields.Contains(_value)))
                                {
                                    Safety_Paddle.Push(true);
                                    Prss_State[Step].St_ReceiveAdvanceFlag = false; //  单个步骤完成后，停止执行该方法代码，避免信息误判
                                    _Prss_Record.Rc_FailInWhy = [string.Empty];
                                }
                            }
                        }
                    }
                    catch (Exception runerror)
                    {
                        if (runerror.Message.Contains("Invalid pattern") && Prss_LongTerm.Lt_CurrentApplyAttribute is not null && !_Prss_State.St_StepRunning_Error)
                        {
                            MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Message, $"当前流程 {Prss_LongTerm.Lt_CurrentApplyAttribute.Step} 正则有误"));
                            _Prss_State.St_StepRunning_Error = true;
                        }
                    }
                }
            }
        }

        private static string GetExecptionAttribute(IEnumerable<string> differents)
        {
            if (differents.Any())
            {
                List<string> Becauses = [];
                foreach (var item in differents)
                {
                    if (ActivityAssistBehivor.Behivor.AttributeTranslationMap.TryGetValue(item, out string? translation) &&
                    translation is not null)
                    {
                        Becauses.Add(translation);
                    }
                }
                return Becauses.Join("、");
            }
            return string.Empty;
        }

        private void TryAdd<Value>(string key, Value value)
        {
            var Factory = FactoryWork(false, FactoryType.Record);

            if (Factory is not null &&
                Factory.Value.Item1 is not null)
            {
                Factory_Record _Prss_Record = Factory.Value.Item1;

                _Prss_Record.Rc_CachePassValue.AddOrUpdate(key,
                    key =>
                {
                    if (value is IEnumerable<string> _values)
                    {
                        return [.. _values];
                    }
                    else
                    {
                        return [value?.GetSafetyChar()];
                    }
                },
                    (key, values) =>
                    {
                        if (value is not null)
                        {
                            if (value is IEnumerable<string> _values)
                            {
                                foreach (var element in _values)
                                {
                                    if (!values.Contains(element)) values.Add(element);
                                }
                            }
                            else
                            {
                                values.Add(value.GetSafetyChar());
                            }
                        }
                        return values;
                });
            }
        }

        private void Recycle()
        {
            var Factory = FactoryWork(false, FactoryType.Record | FactoryType.State);

            if (Factory is not null &&
                Factory.Value.Item1 is not null &&
                Factory.Value.Item3 is not null)
            {
                Factory_Record _Prss_Record = Factory.Value.Item1;

                Factory_State _Prss_State = Factory.Value.Item3;

                if (_Prss_State.St_StepAwait || !_Prss_State.St_DirectExecute)
                {
                    _Prss_Record.Rc_SerialPortoutPut.Clear();
                    _Prss_State.St_DelAwait_Reset_Watch = !_Prss_State.St_DirectExecute;
                    _Prss_State.St_DirectExecute = !_Prss_State.St_DirectExecute;
                    Logger.Print(RuntimeLog.LogType.Debug, $"recycle init: [St_DelAwait_Reset_Watch, {_Prss_State.St_DelAwait_Reset_Watch}], " +
                                      $"[St_DirectExecute, {_Prss_State.St_DirectExecute}]");
                }
            }
        }

        /// <summary>
        /// <para> DeviceContent - 设备输出的内容 </para>
        /// <para> ArgumantConetnt - 参数设置的内容 </para>
        /// <para> XorcheckBack - 结果回调 0 未设置位或、1 通过、2不通过 + 设备位异或 + 参数位异或</para>
        /// </summary>
        /// <param name="content"></param>
        /// <param name="_dvcxor"></param>
        /// <param name="ResultBack"></param>
        /// <param name="UnXorcheckBack"></param>
        private static void XorVerifyInContain(string ArgumentContent, string DeviceXor, Action<(int, string, string)> XorcheckBack, bool IsXorVerify = true)
        {
            string ArgumentXor = ArgumentContent.GetXORcode();

            if (!string.IsNullOrEmpty(ArgumentContent))
            {
                if (IsXorVerify)
                {
                    if (!string.IsNullOrEmpty(DeviceXor))
                    {
                        if (DeviceXor == ArgumentXor)
                        {
                            XorcheckBack.Invoke((1, DeviceXor, ArgumentXor));
                        }
                        else
                        {
                            XorcheckBack.Invoke((2, DeviceXor, ArgumentXor));
                        }
                    }
                }
                else
                {
                    XorcheckBack.Invoke((0, DeviceXor, ArgumentXor));
                }
            }
        }

        private void TaskRelease(bool isException)
        {
            var Factory = FactoryWork(false, FactoryType.Record);

            if (Factory is not null &&
                Factory.Value.Item1 is not null)
            {
                if (Prss_LongTerm.Lt_CurrentApplyAttribute is not null &&
                isException &&
                ActivityAssistBehivor.Behivor.LongTimeTak.Contains(Prss_LongTerm.Lt_CurrentApplyCommand))
                {
                    isLongTimeAtrribute = true;
                }
                else
                {
                    isLongTimeAtrribute = false;
                }
            }

            Prss_State.Clear();
            Prss_Record.Clear();
            Prss_Value.Clear();
            Prss_LongTerm.Lt_StatiSticalSteps.Clear();
            Prss_LongTerm.Lt_StatiSticalSubjoins.Clear();
            Prss_LongTerm.Lt_CurrentApplyAttribute = null; //  这是一个步骤对象，主动设置为null
            ProductBlueCache.Signal = null; //  重置蓝牙信号值

            WorkIndex = 0;
            ProductBlueCache.Close(1);
            Safety_Gate.Push(false);
            if (ReuseOutTimer.IsEnabled) ReuseOutTimer.Stop();
            Logger.Print(RuntimeLog.LogType.Debug, "test process release");
        }

        private async Task CommandAppend(string value)
        {
            void INFOEMPTYERROR()
            {
				MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Question, new CustomMessageBox.InquiryPopupField()
				{
					title = "数据库数据查找",
					message = "匹配数据为空，请进入 [参数设置] 选择或输入基本参数信息",
					options = ["知道了"]
				}));

				Safety_Gate.Push(false);

				MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Initialize, null));
			}

            var Factory = FactoryWork(false, FactoryType.Record | FactoryType.Value | FactoryType.State);

            if (Factory is not null &&
                Factory.Value.Item1 is not null &&
                Factory.Value.Item2 is not null &&
                Factory.Value.Item3 is not null)
            {
                Factory_Record _Prss_Record = Factory.Value.Item1;

                Factory_Value _Prss_Value = Factory.Value.Item2;

                Factory_State _Prss_State = Factory.Value.Item3;

                if (Prss_LongTerm.Lt_CurrentApplyAttribute is not null)
                {
                    bool IsXorVerify = false;
                    string AppendType = string.Empty;
                    if (Prss_LongTerm.Lt_CurrentApplyAttribute.IsXorVerify is not null and bool _IsXorVerify && _IsXorVerify)
                    {
                        IsXorVerify = _IsXorVerify;
                    }

                    if (Prss_LongTerm.Lt_CurrentApplyAttribute.AppendType is not null and string _AppendType)
                    {
                        AppendType = _AppendType;
                    }

                    List<string> CombinationCommands = [];

                    switch (AppendType)
                    {
                        case "蓝牙":

                            await ProductBlueCache.Match(value);

                            if (_Prss_State.St_IsBluetoothBoard && !ProductBlueCache.BluetoothSerial.IsOpen)
                            {
                                await SelectionBlueSerialPort();

                                await OpenSelectionBlue();
                            }

                            if (value == "数据库") //  不为空走设置流程
                            {
                                if (string.IsNullOrEmpty(ProductBlueCache.Address))
                                {
                                    INFOEMPTYERROR();
								}
                                else
                                {
                                    if (!string.IsNullOrEmpty(ProductBlueCache.Regex.Match(ProductBlueCache.Address).Value))
                                    {
                                        string combine = RegExp.RegExpBlueSeparator().Split(ProductBlueCache.Address).Join(_Prss_Value.CurBluethAccording);
                                        
                                        if (!Prss_LongTerm.Lt_CurrentApplyCommand.Contains(combine))
                                        {
                                            CombinationCommands = [Prss_LongTerm.Lt_CurrentApplyCommand, combine];
                                            Prss_LongTerm.Lt_CurrentApplyCommand = CombinationCommands.Join(_Prss_Value.CurAddtionAccording);

                                            if (IsXorVerify) Prss_LongTerm.Lt_CurrentApplyCommand += "," + combine.GetXORcode();

                                        }
                                    }
                                }
                                Recycle();
                            }

                            else
                            {
                                if (string.IsNullOrEmpty(ProductBlueCache.Regex.Match(ProductBlueCache.Address).Value))
                                {
                                    string randomBlue;
                                    if (_Prss_Value.CurBluethAccording == "-")
                                    {
                                        randomBlue = 6.GetDesorderlyBlue(true);
                                    }
                                    else
                                    {
                                        randomBlue = 6.GetDesorderlyBlue();
                                    }
                                    string combine = RegExp.RegExpBlueSeparator().Split(randomBlue).Join(_Prss_Value.CurBluethAccording);
                                    //  使用正则判断，因为是随机的数值
                                    bool isAdded = string.IsNullOrEmpty(ProductBlueCache.Regex.Match(Prss_LongTerm.Lt_CurrentApplyCommand).Value);
                                    if (isAdded)
                                    {
                                        CombinationCommands = [Prss_LongTerm.Lt_CurrentApplyCommand, combine];
                                        Prss_LongTerm.Lt_CurrentApplyCommand = CombinationCommands.Join(_Prss_Value.CurAddtionAccording);
                                        if (IsXorVerify) Prss_LongTerm.Lt_CurrentApplyCommand += "," + combine.GetXORcode();
                                    }
                                    Recycle();

                                }
                                else
                                {
                                    string combine = RegExp.RegExpBlueSeparator().Split(ProductBlueCache.Address).Join(_Prss_Value.CurBluethAccording);
                                    if (!Prss_LongTerm.Lt_CurrentApplyCommand.Contains(combine))
                                    {
                                        CombinationCommands = [Prss_LongTerm.Lt_CurrentApplyCommand, combine];
                                        Prss_LongTerm.Lt_CurrentApplyCommand = CombinationCommands.Join(_Prss_Value.CurAddtionAccording);
                                        if (IsXorVerify) Prss_LongTerm.Lt_CurrentApplyCommand += "," + combine.GetXORcode();
                                    }
                                    Recycle();
                                }
                            }
                            break;

                        case "序列号":
                            if (string.IsNullOrEmpty(BSDT.SN))
                            {
                                INFOEMPTYERROR();
                            }
                            else
                            {
                                if (value == "数据库")
                                {
                                    if (!Prss_LongTerm.Lt_CurrentApplyCommand.Contains(BSDT.SN))
                                    {
                                        CombinationCommands = [Prss_LongTerm.Lt_CurrentApplyCommand, BSDT.SN];
                                        Prss_LongTerm.Lt_CurrentApplyCommand = CombinationCommands.Join(_Prss_Value.CurAddtionAccording);
                                        if (IsXorVerify) Prss_LongTerm.Lt_CurrentApplyCommand += "," + BSDT.SN.GetXORcode();
                                    }
                                }
                                else
                                {
                                    if (RegExp.RegExp0_9a_Z().Match(value).Length == value.Length)
                                    {
                                        if (!Prss_LongTerm.Lt_CurrentApplyCommand.Contains(value))
                                        {
                                            CombinationCommands = [Prss_LongTerm.Lt_CurrentApplyCommand, value];
                                            Prss_LongTerm.Lt_CurrentApplyCommand = CombinationCommands.Join(_Prss_Value.CurAddtionAccording);
                                            if (IsXorVerify) Prss_LongTerm.Lt_CurrentApplyCommand += "," + value.GetXORcode();
                                        }
                                    }
                                }
                            }
                            Recycle();
                            break;

                        case "IMEI号":
                            if (string.IsNullOrEmpty(BSDT.IMEI))
                            {
                                INFOEMPTYERROR();
                            }
                            else
                            {
                                if (value == "数据库")
                                {
                                    if (!Prss_LongTerm.Lt_CurrentApplyCommand.Contains(BSDT.IMEI))
                                    {
                                        CombinationCommands = [Prss_LongTerm.Lt_CurrentApplyCommand, BSDT.IMEI];
                                        Prss_LongTerm.Lt_CurrentApplyCommand = CombinationCommands.Join(_Prss_Value.CurAddtionAccording);
                                        if (IsXorVerify) Prss_LongTerm.Lt_CurrentApplyCommand += "," + BSDT.IMEI.GetXORcode();
                                    }
                                }
                                else
                                {
                                    if (RegExp.RegExp0_9a_Z().Match(value).Length == value.Length)
                                    {
                                        if (!Prss_LongTerm.Lt_CurrentApplyCommand.Contains(value))
                                        {
                                            CombinationCommands = [Prss_LongTerm.Lt_CurrentApplyCommand, value];
                                            Prss_LongTerm.Lt_CurrentApplyCommand = CombinationCommands.Join(_Prss_Value.CurAddtionAccording);
                                            if (IsXorVerify) Prss_LongTerm.Lt_CurrentApplyCommand += "," + value.GetXORcode();
                                        }
                                    }

                                }
                            }
                            Recycle();
                            break;

                        case "DOID":
                            if (string.IsNullOrEmpty(BSDT.DOID))
                            {
                                INFOEMPTYERROR();
                            }
                            else
                            {
                                if (value == "数据库")
                                {
                                    if (!Prss_LongTerm.Lt_CurrentApplyCommand.Contains(BSDT.DOID))
                                    {
                                        CombinationCommands = [Prss_LongTerm.Lt_CurrentApplyCommand, BSDT.DOID];
                                        Prss_LongTerm.Lt_CurrentApplyCommand = CombinationCommands.Join(_Prss_Value.CurAddtionAccording);
                                        if (IsXorVerify) Prss_LongTerm.Lt_CurrentApplyCommand += "," + BSDT.DOID.GetXORcode();
                                    }
                                }
                                else
                                {
                                    if (RegExp.RegExp0_9a_Z().Match(value).Length == value.Length)
                                    {
                                        if (!Prss_LongTerm.Lt_CurrentApplyCommand.Contains(value))
                                        {
                                            CombinationCommands = [Prss_LongTerm.Lt_CurrentApplyCommand, value];
                                            Prss_LongTerm.Lt_CurrentApplyCommand = CombinationCommands.Join(_Prss_Value.CurAddtionAccording);
                                            if (IsXorVerify) Prss_LongTerm.Lt_CurrentApplyCommand += "," + value.GetXORcode();
                                        }
                                    }
                                }
                            }
                            Recycle();
                            break;

                        default:

                            if (!Prss_LongTerm.Lt_CurrentApplyCommand.Contains(value))
                            {
                                Logger.Print(RuntimeLog.LogType.Fatal, "00", Prss_LongTerm.Lt_CurrentApplyCommand, value);
                                CombinationCommands = [Prss_LongTerm.Lt_CurrentApplyCommand, value];
                                Prss_LongTerm.Lt_CurrentApplyCommand = CombinationCommands.Join(_Prss_Value.CurAddtionAccording);
                                if (IsXorVerify) Prss_LongTerm.Lt_CurrentApplyCommand += "," + value.GetXORcode();
                                Logger.Print(RuntimeLog.LogType.Fatal, "11", Prss_LongTerm.Lt_CurrentApplyCommand, value);
                            }
                            Recycle();
                            break;
                    }
                }
            }
        }

        public void Start(bool state = true)
        {
            if (state && WorkIndex != 0) WorkIndex = 0; //  保险措施
            Safety_Gate.Push(state);

            var Factory = FactoryWork(false, FactoryType.State);

            if (Factory is not null &&
                Factory.Value.Item3 is not null)
            {
                Factory_State _Prss_State = Factory.Value.Item3;

                if (!state)
                {
                    _Prss_State.St_DirectExecute = true;
                    _Prss_State.St_DelAwait_Reset_Watch = true;
                }
            }
        }

        private async Task FlagVerify(bool isGreedy = false, Action<List<string>>? FlagCallBack = null)
        {
            List<string> GetPreviousFlag(int flagDesc)
            {
                List<string> Flags = [];
                foreach (var kvp in ActivityAssistBehivor.Behivor.TestFlagsMap)
                {
                    string[] splitKey = RegExp.RegExpSpecial().Split(kvp.Key);
                    if (kvp.Value.Item2 < flagDesc && splitKey.Length >= 2)
                    {
                        Flags.Add(splitKey.ElementAt(1));
                    }
                }
                return Flags;
            }

            //  标识产品名称 - 标识 - 标识工序名称 - 序号
            (string, string, string, int)? GetRealFlag(Factory_Record _Prss_Record)
            {
                if (_Prss_Record.Rc_DeviceFlag is not null) return _Prss_Record.Rc_DeviceFlag;

                foreach (var pair in _Prss_Record.Rc_CachePassValue)
                {
                    List<string> passValues = [.. pair.Value];

                    foreach (var _pass in passValues) //  当前工序通过值
                    {
                        foreach (var kvp in ActivityAssistBehivor.Behivor.TestFlagsMap)
                        {
                            string[] splitKey = RegExp.RegExpSpecial().Split(kvp.Key);
                            if (splitKey.Length >= 2 && splitKey.ElementAt(1) == _pass)
                            {
                                if (_Prss_Record.Rc_DeviceFlag is null)
                                {
                                    _Prss_Record.Rc_DeviceFlag = (splitKey.ElementAt(0), _pass, kvp.Value.Item1, kvp.Value.Item2);
                                    return _Prss_Record.Rc_DeviceFlag;
                                }
                            }
                        }
                    }
                }
                return null;
            }

            await Task.Run(() =>
            {
                var Factory = FactoryWork(false, FactoryType.Record);

                if (Factory is not null &&
                    Factory.Value.Item1 is not null &&
                    Prss_LongTerm.Lt_CurrentApplyAttribute is not null)
                {
                    Factory_Record _Prss_Record = Factory.Value.Item1;

                    if (Prss_LongTerm.Lt_CurrentApplyAttribute.Command.Contains("READ_FLAG"))
                    {
                        List<string> TestFlags = [.. ActivityAssistBehivor.Behivor.TestFlagsMap.Keys]; //  字典key值集合
                        //  标识产品名称 - 标识 - 标识工序名称 - 序号
                        (string, string, string, int)? MatchFlags = GetRealFlag(_Prss_Record);
                        if (MatchFlags is not null) { 
                            string behivor_flag = MatchFlags.Value.Item2; //  字典标识
                            string behivor_prdflag = MatchFlags.Value.Item1; //  字典标识名称
                            string? current_flag = Prss_LongTerm.Lt_CurrentApplyAttribute.PassValueVirify; //  当前工序标识
                            string current_flagname = string.Empty; //  当前工序标识名称
                            int current_flag_desc = -1;
                            if (ActivityAssistBehivor.Behivor.TestFlagsMap.TryGetValue($"{BSDT.PRDFLAG}-{current_flag}", out (string, int) _flagArray))
                            {
                                current_flagname = _flagArray.Item1; //  尝试查找当前工序标识名称名保存它
                                current_flag_desc = _flagArray.Item2; //  尝试查找当前工序顺序并保存它
                            }
                            if (isGreedy)
                            {
                                if (current_flag_desc != -1 && MatchFlags.Value.Item4 > current_flag_desc)//  设备当前标识领先于预期标识
                                {
                                    MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Message, $"当前标识 [{MatchFlags.Value.Item2} - {MatchFlags.Value.Item3}] " +
                                        $"领先于预期的 [{current_flag} - {current_flagname}] 标识，测试通过"));

                                    FlagCallBack?.Invoke(GetPreviousFlag(MatchFlags.Value.Item4));

                                }
                                else if (current_flag_desc != -1 && MatchFlags.Value.Item4 == current_flag_desc)
                                {
                                    MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Message, $"当前标识 [{MatchFlags.Value.Item2} - {MatchFlags.Value.Item3}] " +
                                        $"符合预期的 [{current_flag} - {current_flagname}] 标识，测试通过"));

                                    FlagCallBack?.Invoke(GetPreviousFlag(MatchFlags.Value.Item4));
                                }
                                else
                                {
                                    MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Message, $"当前标识 [{MatchFlags.Value.Item2} - {MatchFlags.Value.Item3}] " +
                                        $"不满足预期的 [{current_flag} - {current_flagname}] 标识，测试不通过"));
                                    FlagCallBack?.Invoke([]);
                                    Start(false);
                                }
                            }
                            else
                            {
                                //  如果产品标识正确，并且当前步骤为校验设备标识，并且通过值与字典标识匹配，并且当前工序预期标识不匹配，开始组合可能原因信息
                                if (behivor_prdflag == BSDT.PRDFLAG && MatchFlags.Value.Item2 == behivor_flag && current_flag is not null && MatchFlags.Value.Item2 != current_flag) //  pass
                                {
                                    //  先给出笼统提示
                                    MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Message, $"当前标识 [{MatchFlags.Value.Item2} - {MatchFlags.Value.Item3}] " +
                                        $"与预期的 [{current_flag} - {current_flagname}] 标识不一致"));

                                    //  字典标识与预期标识, 
                                    if (current_flag_desc != -1 && MatchFlags.Value.Item4 > current_flag_desc)//  设备当前标识领先于预期标识
                                    {
                                        if (MatchFlags.Value.Item4 - current_flag_desc == 1) //  pass
                                        {
                                            List<string> suplusStep = [];
                                            IEnumerable<string> totalStep = ActivityAssistBehivor.Behivor.TestFlagsMap.Values
                                                .Where(x => x.Item2 > MatchFlags.Value.Item4)
                                                .Select(x => x.Item1);
                                            foreach (var step in totalStep)
                                            {
                                                if (!suplusStep.Contains(step)) suplusStep.Add(step);
                                            }

                                            if (suplusStep.Count > 0) //  如果还存在剩余工序则提示
                                            {
                                                MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Message, $"当前工序 [{MatchFlags.Value.Item3}] 在预期工序 [{current_flagname}] 之后, " +
                                                    $"请选择剩余 [{suplusStep.Join("、")}] 工序进行测试"));
                                            }
                                            else //  否则即为最终工序
                                            {
                                                MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Message,
                                                     new EnjoyRichTextBox.Text
                                                     {
                                                         TxType = EnjoyRichTextBox.TextType.HyperLink,
                                                         Contnet = $"当前工序 [{MatchFlags.Value.Item3}] 在预期工序 [{current_flagname}] 之后, " + $"当前已是最终工序，所有产测工序已完成",
                                                         FontSize = 20,
                                                         Foreground = "ElectricLime"
                                                     }));
                                            }
                                        }
                                        else
                                        {
                                            List<string> suplusStep = [];
                                            IEnumerable<string> totalStep1 = ActivityAssistBehivor.Behivor.TestFlagsMap.Values
                                                .Where(x => x.Item2 < MatchFlags.Value.Item4 && x.Item2 > current_flag_desc)
                                                .Select(x => x.Item1);
                                            foreach (var step in totalStep1)
                                            {
                                                if (!suplusStep.Contains(step)) suplusStep.Add(step);
                                            }

                                            List<string> expectStep = [];
                                            IEnumerable<string> totalStep2 = ActivityAssistBehivor.Behivor.TestFlagsMap.Values
                                                .Where(x => x.Item2 > MatchFlags.Value.Item4)
                                                .Select(x => x.Item1);
                                            foreach (var step in totalStep2)
                                            {
                                                if (!expectStep.Contains(step)) expectStep.Add(step);
                                            }

                                            if (expectStep.Count == 0)
                                            {
                                                MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Message,
                                                   new EnjoyRichTextBox.Text
                                                   {
                                                       TxType = EnjoyRichTextBox.TextType.HyperLink,
                                                       Contnet = $"当前工序 [{MatchFlags.Value.Item3}] 和预期工序 [{current_flagname}] 非紧密工序, " +
                                                                 $"差异 [{suplusStep.Join("、")}] 工序, 当前已是最终工序，所有产测工序已完成测试",
                                                       FontSize = 20,
                                                       Foreground = "ElectricLime"
                                                   }));
                                            }
                                            else
                                            {
                                                MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Message, $"当前工序 [{MatchFlags.Value.Item3}] 和预期工序 [{current_flagname}] 非紧密工序, " +
                                                    $"差异 [{suplusStep.Join("、")}] 工序, 请选择 [{expectStep.Join("、")}] 工序进行测试"));
                                            }
                                        }
                                    }
                                    else if (current_flag_desc != -1 && MatchFlags.Value.Item4 < current_flag_desc) //  设备当前标识落后于预期标识
                                    {
                                        if (MatchFlags.Value.Item4 - current_flag_desc != 1)
                                        {
                                            List<string> suplusStep = [];
                                            IEnumerable<string> totalStep = ActivityAssistBehivor.Behivor.TestFlagsMap.Values
                                                .Where(x => x.Item2 <= current_flag_desc && x.Item2 > MatchFlags.Value.Item4)
                                                .Select(x => x.Item1);
                                            foreach (var step in totalStep)
                                            {
                                                if (!suplusStep.Contains(step)) suplusStep.Add(step);
                                            }

                                            MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Message, $"当前工序 [{MatchFlags.Value.Item3}] 和预期工序 [{current_flagname}] 非紧密工序, " +
                                                $"请先完成 [{suplusStep.Join("、")}] 工序后再执行当前工序"));
                                        }
                                    }
                                }

                            }
                        }
                    }
                }
            });
        }

        public bool State()
        {
            if (Safety_Gate.TryPeek(out bool St_ProcessRunning))
            {
                return St_ProcessRunning;
            }
            return false;
        }

        public void IsAwait(bool isAwait = true)
        {
            var Factory = FactoryWork(false, FactoryType.State);

            if (Factory is not null &&
                Factory.Value.Item3 is not null)
            {
                Factory_State _Prss_State = Factory.Value.Item3;

                _Prss_State.St_StepAwait = isAwait;
            }
        }

        public void SendQuestioning(CustomMessageBox.InquiryPopupInvoke invoke)
        {
            var Factory = FactoryWork(false, FactoryType.Record);

            if (Factory is not null &&
                Factory.Value.Item1 is not null)
            {
                Factory_Record _Prss_Record = Factory.Value.Item1;

                _Prss_Record.Rc_QuestioningReturn = invoke;
            }
        }

        public async Task SetMainAccording(string imei, string sn, string bluetooth, string doid, string? qr1, string? qr2)
        {
            async Task<bool> QR(string qr)
            {
                MessagePro?.Invoke(new FlyingDove(MessageProPlantType.DimProcess, new KeyValuePair<double, string>(1, "条码校验中...")));
                Dictionary<string, string> QRmap = await ExtraFromQrcode(qr);

                bool _verify = false;

                if (QRmap.TryGetValue("error", out string? _error))
                {
                    MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Question, new CustomMessageBox.InquiryPopupField()
                    {
                        title = "参数错误",
                        type = 1,
                        message = $"条码信息中 [{_error}] 与 当前参数不一致",
                        options = ["知道了"]
                    }));
                    _verify = false;
                }

                if (QRmap.TryGetValue("id", out string? _id) &&
                    QRmap.TryGetValue("imei", out string? _imei) &&
                    QRmap.TryGetValue("sn", out string? _sn) &&
                    QRmap.TryGetValue("blue", out string? _blue))
                {

                    if (!string.IsNullOrEmpty(imei) &&
                        !string.IsNullOrEmpty(sn) &&
                        !string.IsNullOrEmpty(doid) &&
                        !string.IsNullOrEmpty(bluetooth))
                    {

                        MessagePro?.Invoke(new FlyingDove(MessageProPlantType.DimProcess, new KeyValuePair<double, string>(5, "条码校验中...")));

                        if (_id != doid)
                        {
                            MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Question, new CustomMessageBox.InquiryPopupField()
                            {
                                title = "参数错误",
                                type = 1,
                                message = $"条码ID [{_id}] 与 当前参数ID [{doid}] 不一致",
                                options = ["知道了"]
                            }));
                            _verify = false;
                        }

                        else if (_imei != imei)
                        {
                            MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Question, new CustomMessageBox.InquiryPopupField()
                            {
                                title = "参数错误",
                                type = 1,
                                message = $"条码IMEI [{_imei}] 与 当前参数IMEI [{imei}] 不一致",
                                options = ["知道了"]
                            }));
                            _verify = false;
                        }

                        else if (_sn != sn)
                        {
                            MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Question, new CustomMessageBox.InquiryPopupField()
                            {
                                title = "参数错误",
                                type = 1,
                                message = $"条码IMEI [{_sn}] 与 当前参数IMEI [{sn}] 不一致",
                                options = ["知道了"]
                            }));
                            _verify = false;
                        }

                        else if (_blue != bluetooth)
                        {
                            MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Question, new CustomMessageBox.InquiryPopupField()
                            {
                                title = "参数错误",
                                type = 1,
                                message = $"条码IMEI [{_blue}] 与 当前参数IMEI [{bluetooth}] 不一致",
                                options = ["知道了"]
                            }));
                            _verify = false;
                        }

                        else
                        {
                            _verify = true;
                        }
                    }
                    else
                    {
                        imei = _imei;
                        sn = _sn;
                        doid = _id;
                        bluetooth = _blue;
                        _verify = true;
                    }
                }
                MessagePro?.Invoke(new FlyingDove(MessageProPlantType.DimProcess, new KeyValuePair<double, string>(10, "条码校验中...")));
                return _verify;
            }

            bool _pass = true;

            if (!string.IsNullOrEmpty(qr1))
            {
                _pass = await QR(qr1);
            }

            if (!string.IsNullOrEmpty(qr2))
            {
                _pass = await QR(qr2);
            }

            if (_pass)
            {
                await ProductBlueCache.Match(bluetooth);
                BSDT.IMEI = imei;
                BSDT.SN = sn;
                BSDT.DOID = doid;
                BSDT.QRCODE_1 = qr1;
                BSDT.QRCODE_2 = qr2;
                ValidValueMaps.AddOrUpdate("SN", sn, (k, v)=>sn);
                ValidValueMaps.AddOrUpdate("IMEI", sn, (k, v) => sn);
                ValidValueMaps.AddOrUpdate("DOID", sn, (k, v) => sn);
                ValidValueMaps.AddOrUpdate("QRCODE_1", sn, (k, v) => sn);
                ValidValueMaps.AddOrUpdate("QRCODE_2", sn, (k, v) => sn);
            }
            else
            {
                Start(false);
            }
            return;
        }

        public static void SetMainAccording(string productFlag)
        {
            BSDT.PRDFLAG = productFlag;
        }

        public void SetAtrributeAlter(IEnumerable<SupplementConfig> Surpoment)
        {
            AtrributeSupplement = [.. Surpoment];
        }

        private async Task SelectionBlueSerialPort()
        {
            var Factory = FactoryWork(false, FactoryType.Record | FactoryType.State);

            if (Factory is not null &&
                Factory.Value.Item1 is not null &&
                Factory.Value.Item3 is not null)
            {
                Factory_Record _Prss_Record = Factory.Value.Item1;

                Factory_State _Prss_State = Factory.Value.Item3;

                if (string.IsNullOrEmpty(ProductBlueCache.Port) && !_Prss_State.St_Bluetooth_SerialPort_Get)
                {
                    _Prss_State.St_Bluetooth_SerialPort_Get = true;

                    ManagementObjectSearcher Cominfos = new(@"SELECT * FROM Win32_PnPEntity WHERE NAME LIKE '%COM%'");
                    List<string> SerialProts = [.. await Cominfos.Com()];

                    MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Question, new CustomMessageBox.InquiryPopupField()
                    {
                        title = "插上蓝牙板并选择它",
                        options = ["确定", "程序关闭前沿用这个蓝牙串口"],
                        itemsSource = SerialProts
                    }));

                    while (Safety_Gate.TryPeek(out bool _Gate) && _Gate)
                    {
                        if (_Prss_Record.Rc_QuestioningReturn is not null &&
                            _Prss_Record.Rc_QuestioningReturn.selectedValues.Count > 0)
                        {
                            ProductBlueCache.Port = RegExp.RegExpSerialCom().Match(_Prss_Record.Rc_QuestioningReturn.selectedValues[0]).Value;
                            break;
                        }
                        await Task.Delay(300);
                    }
                    
                }
            }
        }

        private async Task OpenSelectionBlue()
        {
            await Task.Run(async () =>
            {
                var Factory = FactoryWork(false, FactoryType.Record);

                if (Factory is not null &&
                    Factory.Value.Item1 is not null)
                {
                    Factory_Record _Prss_Record = Factory.Value.Item1;

                    if (Safety_Gate.TryPeek(out bool _Gate) && _Gate)
                    {
                        Stopwatch stopwatch = Stopwatch.StartNew();
                        while (string.IsNullOrEmpty(ProductBlueCache.Port))
                        {
                            await Task.Delay(200);
                            if (stopwatch.ElapsedMilliseconds > 5000) break;
                        }
                    }

                    try
                    {
                        if (!ProductBlueCache.BluetoothSerial.IsOpen)
                        {
                            ProductBlueCache.BluetoothSerial.PortName = ProductBlueCache.Port;
                            ProductBlueCache.Open();
                            MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Message,
                                               $"打开串口{ProductBlueCache.BluetoothSerial.PortName}, 状态: {ProductBlueCache.BluetoothSerial.IsOpen}"));
                        }

                        if (_Prss_Record.Rc_QuestioningReturn is not null &&
                            _Prss_Record.Rc_QuestioningReturn.index != 1)
                        {
                            ProductBlueCache.Port = string.Empty; //  不沿用
                        }
                        _Prss_Record.Rc_QuestioningReturn = null;

                    }
                    catch (Exception error)
                    {
                        _Prss_Record.Rc_QuestioningReturn = null;
                        _Prss_Record.Rc_FailInWhy = ["检查:\n1.串口信息截取失败\n2.串口选择错误\n3.串口被占用"];
                        Logger.Print(RuntimeLog.LogType.Error, $"blue serial open error: {error.Message}");
                    }
                }
            });
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="qrcode"></param>
        /// <returns>(string, string, string, string) - id, imei, sn, blue</returns>
        private async Task<Dictionary<string, string>> ExtraFromQrcode(string qrcode)
        {
            static WorkOrderUnfold? Add(object result)
            {
                WorkOrderUnfold? OrderUnfold = null;
                if (result is not null and Supabase.Postgrest.Responses.ModeledResponse<WorkOrderUnfold> cloudResult)
                {
                    foreach (var model in cloudResult.Models)
                    {
                        if (OrderUnfold == null)
                        {
                            OrderUnfold = model;
                        }
                        else
                        {
                            if (OrderUnfold.Imei != model.Imei)
                            {
                                OrderUnfold = null;
                                break;
                            }
                        }
                    }
                }
                else
                {
                    if (result is not null and Dictionary<string, List<object>> localResult &&
                        localResult.Count > 0 &&
                        localResult.TryGetValue("id", out List<object>? ids) &&
                        localResult.TryGetValue("imei", out List<object>? imeis) &&
                        localResult.TryGetValue("sn", out List<object>? sns) &&
                        localResult.TryGetValue("blue_mac", out List<object>? blues))
                    {
                        for (int index = 0; index < ids.Count; index++)
                        {
                            if (OrderUnfold == null)
                            {
                                OrderUnfold = new WorkOrderUnfold
                                {
                                    Id = ids[index].GetSafetyChar(),
                                    Imei = imeis[index].GetSafetyChar(),
                                    Sn = sns[index].GetSafetyChar(),
                                    BlueMac = blues[index].GetSafetyChar()
                                };
                            }
                            else
                            {
                                if (OrderUnfold.Imei != imeis[index].GetSafetyChar())
                                {
                                    OrderUnfold = null;
                                    break;
                                }
                            }
                        }
                    }
                }
                return OrderUnfold;
            }

            Dictionary<string, string> resultMap = [];
            List<string> matchKeyworks = [];

            Dictionary<int, string> matchAll = qrcode.MatchAll("[0-9a-zA-Z]{15,20}");

            if (matchAll != null) matchKeyworks.AddRange(matchAll.Values);

            BSDT.QRCODE.Clear();

            OrderFilterCondition.FieldType FieldType = OrderFilterCondition.FieldType.IMEI;
            foreach (var kw in matchKeyworks)
            {
                bool _stat = false;

                object? result = await Server_Activity.AutoFindDim(new OrderFilterCondition()
                {
                    FilterConditions = [ 
                    new OrderFilterCondition.Condition() 
                    { 
                        FilterContent = kw,
                        FilterFieldType = FieldType
                    }]
                });
                if (result is not null)
                {
                    if (Add(result) is not null and WorkOrderUnfold Unfold)
                    {
                        resultMap.TryAdd("id", Unfold.Id);
                        resultMap.TryAdd("imei", Unfold.Imei);
                        resultMap.TryAdd("sn", Unfold.Sn);
                        resultMap.TryAdd("blue", Unfold.BlueMac);

                        BSDT.QRCODE.Add(kw);
                        foreach (var surplus in matchKeyworks.Where(x => x != kw))
                        {
                            if (surplus == Unfold.Id) BSDT.QRCODE.Add("DOID");
                            if (surplus == Unfold.Imei) BSDT.QRCODE.Add("IMEI");
                            if (surplus == Unfold.Sn) BSDT.QRCODE.Add("SN");
                            if (surplus == Unfold.BlueMac) BSDT.QRCODE.Add("BLUE");
                        }
                    }
                    _stat = true;
                    break;
                }
                else
                {
                    if (FieldType == OrderFilterCondition.FieldType.IMEI)
                    {
                        FieldType = OrderFilterCondition.FieldType.SN;
                    }
                    else if (FieldType == OrderFilterCondition.FieldType.SN)
                    {
                        FieldType = OrderFilterCondition.FieldType.IMEI;
                    }
                }

                if (!_stat)
                {
                    resultMap.Clear();
                    resultMap.Add("error", kw);
                    break;
                }
            }
            return resultMap;
        }

        /// <summary>
        /// 0 - write, 1 - read，曾报错值不能为空，将IMEI作为参数传参之后，就没有这个问题了，可能是线程中竞争导致了资源异常，读到了空值
        /// </summary>
        /// <param name="iemi"></param>
        /// <param name="action"></param>
        /// <param name="callback"></param>
        /// <returns></returns>
        private async Task WriteDBUseTraces(string IMEI, int action, Action? callback, Action<string>? errorback)
        {
            try
            {
                DB.DB_TYPE DBTYPE = await Server_DB.CheckDBSurvival(DB.G_MapKeyName(DB.DB_MAPKEY.LocalDataCache));

                if (DBTYPE == DB.DB_TYPE.DB_Cloud)
                {
                    if (Server_DB.GetCloudDB() is not null and Supabase.Client CloudDB)
                    {
                        async Task query()
                        {
                            if (action == 0)
                            {
                                await CloudDB.From<WorkOrderUnfold>()
                                    .Set(x => x.UsingTime, DateTime.Now.ToString())
                                    .Where(x => x.Imei == IMEI)
                                    .Update();
                            }
                            else if (action == 1)
                            {
                                await CloudDB.From<WorkOrderUnfold>()
                                    .Set(x => x.VerifyTime, DateTime.Now.ToString())
                                    .Where(x => x.Imei == IMEI)
                                    .Update();
                            }
                        }

                        await Server_DB.CloudAnchorChannel<WorkOrderUnfold>(async () =>
                        {
                            Supabase.Postgrest.Responses.ModeledResponse<WorkOrderUnfold>? Response = null;

                            if (action == 0)
                            {
                                Response = await CloudDB.From<WorkOrderUnfold>()
                                    .Select(x => new object[] { x.UsingTime })
                                    .Where(x => x.Imei == IMEI)
                                    .Get();

                            }
                            else if (action == 1)
                            {
                                Response = await CloudDB.From<WorkOrderUnfold>()
                                    .Select(x => new object[] { x.VerifyTime })
                                    .Where(x => x.Imei == IMEI)
                                    .Get();
                            }

                            if (Response is not null &&
                                Response.Model is not null)
                            {
                                if (action == 0 && !string.IsNullOrEmpty(Response.Model.UsingTime))
                                {
                                    callback?.Invoke();
                                }
                                else if (action == 1 && !string.IsNullOrEmpty(Response.Model.VerifyTime))
                                {
                                    callback?.Invoke();
                                }
                            }
                        },
                        async () =>
                        {
                            await query();
                        }
                        , null

                        , "UPDATE");
                    }
                }

                else if (DBTYPE == DB.DB_TYPE.DB_Local)
                {
                    string KeyField = "using_time";

                    if (action == 1) KeyField = "verify_time";

                    string updateCommandSql = $"UPDATE workorder_unfold SET {KeyField}='{DateTime.Now}' WHERE imei='{BSDT.IMEI}'";

                    if (await Server_DB.LocalDBQueryFree(updateCommandSql) != null)
                    {
                        string reQueryCommandSql = $"SELECT {KeyField} FROM workorder_unfold WHERE imei='{BSDT.IMEI}'";

                        SqliteExceuteResult Result = await Server_DB.LocalDBQueryFree(reQueryCommandSql);

                        if (Result.ErrorHint is not null)
                        {
                            errorback?.Invoke(Result.ErrorHint);
                        }
                        else
                        {
                            if (Result.Result.TryGetValue(reQueryCommandSql, out Dictionary<string, ICollection<object>>? queryResult))
                            {
                                if (queryResult.TryGetValue(KeyField, out ICollection<object>? _time) &&
                                    _time.Count == 1 &&
                                    !string.IsNullOrEmpty(_time.First().GetSafetyChar()))
                                {
                                    callback?.Invoke();
                                }
                            }
                        }
                    }
                }
                
                Logger.Print(RuntimeLog.LogType.Debug, $"WriteDBUseTraces action finish");
            }
            catch (Exception error)
            {
                Logger.Print(RuntimeLog.LogType.Debug, $"register product encount error: {error.Message}");
                errorback?.Invoke(error.Message);
            }
        }

        private async Task<(bool, bool)> GetDataSectionValid(string IMEI)
        {
            (bool, bool) valid = (false, false);

            TaskCompletionSource resultSource = new ();

            DB.DB_TYPE DBTYPE = await Server_DB.CheckDBSurvival(DB.G_MapKeyName(DB.DB_MAPKEY.LocalDataCache));

            if (DBTYPE == DB.DB_TYPE.DB_Cloud)
            {
                if (Server_DB.GetCloudDB() is not null and Supabase.Client CloudDB && !string.IsNullOrEmpty(IMEI))
                {
                    var queryResult = await CloudDB.From<WorkOrderUnfold>()
                           .Where(x => x.Imei == IMEI)
                           .Get();

                    if (queryResult.Model is not null && queryResult.Models.Count == 1)
                    {
                        if (!string.IsNullOrEmpty(queryResult.Model.UsingTime))
                        {
                            valid.Item1 = true;
                        }

                        if (!string.IsNullOrEmpty(queryResult.Model.VerifyTime))
                        {
                            valid.Item2 = true;
                        }
                    }
                }
            }

            else if (DBTYPE == DB.DB_TYPE.DB_Local)
            {
                string queryCommandSql = $"SELECT using_time,verify_time FROM workorder_unfold WHERE imei='{IMEI}'";

                if (await Server_DB.LocalDBQueryFree(queryCommandSql) is not null and SqliteExceuteResult _queryResult &&
                    _queryResult.ErrorHint is null &&
                    _queryResult.Result.TryGetValue(queryCommandSql, out Dictionary<string, ICollection<object>>? __resultMap))
                {
                    if (__resultMap.TryGetValue("using_time", out ICollection<object>? _using_time) &&
                        _using_time.Count == 1 &&
                        !string.IsNullOrEmpty(_using_time.First().GetSafetyChar()))
                    {
                        valid.Item1 = true;
                    }

                    if (__resultMap.TryGetValue("verify_time", out ICollection<object>? _verify_time) &&
                        _verify_time.Count == 1 &&
                        !string.IsNullOrEmpty(_verify_time.First().GetSafetyChar()))
                    {
                        valid.Item2 = true;
                    }
                }
            }

            resultSource.SetResult();
            
            await resultSource.Task;

            Logger.Print(RuntimeLog.LogType.Debug, $"GetDataSectionValid verify success");

            return valid;
        }

        private async Task DataAllowableEntry()
        {
            var Factory = FactoryWork(false, FactoryType.Record | FactoryType.State);

            if (Factory is not null &&
                Factory.Value.Item1 is not null &&
                Factory.Value.Item3 is not null)
            {
                Factory_Record _Prss_Record = Factory.Value.Item1;

                Factory_State _Prss_State = Factory.Value.Item3;

                string Step = Factory.Value.Item4;

                List<string> _Types = [];
                if (_Prss_Record.Rc_AlowableEntryType.Contains(','))
                {
                    _Types.AddRange(_Prss_Record.Rc_AlowableEntryType.Split(','));
                }
                else
                {
                    _Types.Add(_Prss_Record.Rc_AlowableEntryType);
                }
                if (_Types.Contains("DB"))
                {
                    string IMEI = BSDT.IMEI;
                    (bool, bool) valid = await GetDataSectionValid(IMEI);

                    if (valid.Item2)
                    {
                        MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Message, $"{BSDT.IMEI} 数据库中已有校号记录"));
                        _Prss_State.St_AllowableNext = false;
                    }

                    if (valid.Item1)
                    {
                        MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Message, $"{BSDT.IMEI} 数据库中已有写号记录,该数据不可再次使用"));
                        _Prss_State.St_AllowableNext = false;
                        Start(false);
                    }
                    _Prss_State.St_AllowableNext = true; //  校验通过时继续走下一个流程
                }

                if (_Types.Contains("HINT")) //  该校验不计入正常流程中
                {
                    MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Question, new CustomMessageBox.InquiryPopupField()
                    {
                        title = Step,
                        message = Prss_LongTerm.Lt_CurrentApplyCommand,
                        type = 1,
                        options = ["取消", "已进入产测"]
                    }));

                    Stopwatch timeout = Stopwatch.StartNew();

                    while (Safety_Gate.TryPeek(out bool _Gate) && _Gate)
                    {
                        if (_Prss_Record.Rc_QuestioningReturn is not null)
                        {
                            if (_Prss_Record.Rc_QuestioningReturn.index == 1)
                            {
                                _Prss_Record.Rc_QuestioningReturn = null;
                                _Prss_State.St_AllowableNext = false;
                                break;
                            }
                            else
                            {
                                _Prss_Record.Rc_QuestioningReturn = null;
                                _Prss_State.St_AllowableNext = false;
                                Start(false);
                                break;
                            }
                        }
                        await Task.Delay(300);

                        if (timeout.ElapsedMilliseconds > 20000) break;
                    }
                }

                void CheckArg(string data, string name)
                {
                    if (!data.IsAbsoluteValidValue())
                    {
                        Start(false);
                        MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Message, $"{name} 不能为空"));
                    }
                }

                if (_Types.Contains(nameof(OrderFilterCondition.FieldType.IMEI))) CheckArg(BSDT.IMEI, nameof(OrderFilterCondition.FieldType.IMEI));
                if (_Types.Contains(nameof(OrderFilterCondition.FieldType.SN)))   CheckArg(BSDT.IMEI, nameof(OrderFilterCondition.FieldType.SN));
                if (_Types.Contains(nameof(OrderFilterCondition.FieldType.DOID))) CheckArg(BSDT.IMEI, nameof(OrderFilterCondition.FieldType.DOID));
                if (_Types.Contains(nameof(OrderFilterCondition.FieldType.BLUE))) CheckArg(BSDT.IMEI, nameof(OrderFilterCondition.FieldType.BLUE));
            }
            Logger.Print(RuntimeLog.LogType.Debug, $"DataAllowableEntry verify success");
        }

        /// <summary>
        /// -1 - invalid  0 - valid 1 - pass 2 - fail
        /// </summary>
        /// <param name="flag"></param>
        /// <param name="_content"></param>
        /// <param name="passBack"></param>
        /// <param name="IsXorVerify"></param>
        private void ContainAtrribute(string flag, string _content, Action<int> ResultCallBack, bool IsXorVerify = true)
        {
            var Factory = FactoryWork(false, FactoryType.State | FactoryType.Record);

            if (Factory is not null && 
                Factory.Value.Item3 is not null &&
                Factory.Value.Item1 is not null)
            {
                Factory_Record _Prss_Record = Factory.Value.Item1;
                Factory_State _Prss_State = Factory.Value.Item3;

                string Format = "{0}\\W+(\\d+)\\W*";

                switch (flag)
                {
                    case "BLUE":
                        if (!string.IsNullOrEmpty(ProductBlueCache.Address))
                        {
                            ResultCallBack.Invoke(0);
                            GroupCollection outputGroups = ProductBlueCache.Regex.Match(_content).Groups;

                            if (outputGroups.Count >= 2 &&
                                outputGroups[1].Value is not null and string DeviceBlue && DeviceBlue.Length > 15)
                            {
                                string spacial = DeviceBlue.Contains(':') ? ":" : "-";
                                string _DeviceBlue = CC_Blue.ReworkAddress(RegExp.RegExpBlueSeparator().Replace(DeviceBlue, spacial));
                                string _ArgumentBlue = RegExp.RegExpBlueSeparator().Replace(ProductBlueCache.Address, spacial);

                                if (_DeviceBlue.Equals(_ArgumentBlue))
                                {
                                    string _DeviceBlueXor = string.Empty;
                                    if (outputGroups.Count >= 3 && outputGroups[2].Value is not null and string _Xor) _DeviceBlueXor = _Xor;
                                    if (!string.IsNullOrEmpty(_DeviceBlueXor))
                                    {

                                        XorVerifyInContain(_ArgumentBlue, _DeviceBlueXor, (code) =>
                                        {
                                            if (code.Item1 == 0)
                                            {
                                                MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Message,
                                                    $"蓝牙地址: {ProductBlueCache.Address} 包含校验通过"));
                                                ResultCallBack.Invoke(1);
                                            }
                                            else if (code.Item1 == 1)
                                            {
                                                MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Message,
                                                    $"蓝牙地址: {ProductBlueCache.Address} 包含校验通过" +
                                                    $", 当前位异或码[ {code.Item2} ]与预期位异或码[ {code.Item3} ]相同，位异或校验通过"));
                                                ResultCallBack.Invoke(1);
                                            }
                                            else if (code.Item1 == 2)
                                            {
                                                MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Message,
                                                    $"蓝牙地址: {ProductBlueCache.Address} 包含校验通过" +
                                                    $", 当前位异或码[ {code.Item2} ]与预期位异或码[ {code.Item3} ]不一致，位异或校验失败"));
                                                ResultCallBack.Invoke(2);
                                            }
                                        }, IsXorVerify);
                                    }

                                    else
                                    {
                                        MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Message,
                                            $"蓝牙地址: {ProductBlueCache.Address} 包含校验通过," +
                                            $"但是检测不到设备输出位异或码，请检查是否需要删除该条属性"));
                                        ResultCallBack.Invoke(1);
                                    }
                                }
                            }
                        }
                        else ResultCallBack.Invoke(-1);
                        break;

                    case "QRCODE":
                        if (BSDT.QRCODE.Count > 0)
                        {
                            ResultCallBack.Invoke(0);
                            int qrIndex = 0;
                            foreach (var qr in BSDT.QRCODE)
                            {
                                if (_content.Contains(qr)) qrIndex++;
                                if (qrIndex == BSDT.QRCODE.Count)
                                {
                                    MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Message, $"QR: {BSDT.QRCODE.Join(", ")} 包含校验通过"));
                                    ResultCallBack.Invoke(1);
                                }
                            }
                        }
                        break;

                    default:

                        if (ValidValueMaps.TryGetValue(flag, out string? ValidValue))
                        {
                            if (!string.IsNullOrEmpty(ValidValue))
                            {
                                ResultCallBack.Invoke(0);
                                string _DeviceBlueXor = string.Empty;
                                GroupCollection outputGroups = Regex.Match(_content, String.Format(Format, ValidValue)).Groups;
                                if (outputGroups.Count >= 2 && outputGroups[1].Value is not null and string _Xor) _DeviceBlueXor = _Xor;

                                if (_content.Contains(ValidValue) && 
                                    !_Prss_State.OnceComditionMap.TryGetValue(flag, out bool _flagState))
                                {
                                    XorVerifyInContain(ValidValue, _DeviceBlueXor, (code) =>
                                    {
                                        if (code.Item1 == 0)
                                        {
                                            MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Message, $"{flag}: {ValidValue} 包含校验通过"));
                                            ResultCallBack.Invoke(1);
                                        }
                                        else if (code.Item1 == 1)
                                        {
                                            MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Message,
                                                $"{flag}: {ValidValue} 包含校验通过" +
                                                $", 当前位异或码[ {code.Item2} ]与预期位异或码[ {code.Item3} ]相同，位异或校验通过"));
                                            ResultCallBack.Invoke(1);
                                        }
                                        else if (code.Item1 == 2)
                                        {
                                            MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Message,
                                                $"{flag}: {ValidValue} 包含校验通过" +
                                                $", 当前位异或码[ {code.Item2} ]与预期位异或码[ {code.Item3} ]不一致，位异或校验失败"));

                                            _Prss_Record.Rc_FailInWhy = ["点击此查看位异或码", 
                                                                         $"包含校验不通过，点击该文本以确认原始输出是否存在包含数据[{flag}]"];

                                            _Prss_Record.Rc_FailInWhyType = [(FailWhyinDisposeType.BitwiseTool, ValidValue),
                                                                             (FailWhyinDisposeType.ContentPopup, null)];

                                            ResultCallBack.Invoke(2);
                                        }
                                        _Prss_State.OnceComditionMap.TryAdd(flag, true);
                                    }, IsXorVerify);
                                }
                                else if (_Prss_Record.Rc_FailInWhy.Count == 0)
                                {
                                    _Prss_Record.Rc_FailInWhy = [$"包含校验不通过，点击该文本以确认原始输出是否存在包含数据[{flag}]"];

                                    _Prss_Record.Rc_FailInWhyType = [(FailWhyinDisposeType.ContentPopup, null)];
                                }
                            }
                            else ResultCallBack.Invoke(-1);
                        }
                        break;
                }
            }
        }

        private async Task RetryProcess()
        {
            FactoryWork(true, FactoryType.State); //  重置产测运行状态

            var Factory = FactoryWork(false, FactoryType.Record | FactoryType.Value | FactoryType.State);

            if (Factory != null && Prss_LongTerm.Lt_CurrentApplyAttribute != null)
            {
                Factory_Record? _Prss_Record = Factory.Value.Item1;
                Factory_Value? _Prss_Value = Factory.Value.Item2;
                Factory_State? _Prss_State = Factory.Value.Item3;

                MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Message, $"{Factory.Value.Item4}->正在重发指令，请注意是否需要手动操作设备"));

                if (_Prss_Record is not null &&
                    _Prss_Value is not null &&
                    _Prss_State is not null)
                {
                    _Prss_Record.Rc_CollectedFields.Clear(); //  清除字段缓存
                    _Prss_State.St_ReceiveAdvanceFlag = true; //  手动设置标识，开始接收串口信息，进行新一轮重试

                    if (Prss_LongTerm.Lt_CurrentApplyAttribute.RetryDelayMs is not null and int RetryDelayMs)
                    {
                        await Task.Delay(RetryDelayMs);
                    }
                    else
                    {
                        await Task.Delay(400);
                    }
                    ExecuteCommand();
                    _Prss_Value.CurRetryCount++;
                }
            }
        }

        /// <summary>
        /// true - Init || false - Get
        /// </summary>
        /// <param name="IsDestory"></param>
        /// <param name="T"></param>
        /// <returns></returns>
        private (Factory_Record?, Factory_Value?, Factory_State?, string)? FactoryWork(bool IsDestory, FactoryType T)
        {
            bool St_Prss_Record = T.HasFlag(FactoryType.Record);
            bool St_Prss_Value = T.HasFlag(FactoryType.Value);
            bool St_Prss_State = T.HasFlag(FactoryType.State);

            Factory_Record? _Prss_Record = null;
            Factory_Value? _Prss_Value = null;
            Factory_State? _Prss_State = null;

            if (Safety_Step.TryPeek(out string? Step))
            {
                if (IsDestory)
                {
                    if (St_Prss_State)
                    {
                        Prss_State.AddOrUpdate(Step, new Factory_State(), (key, oldValue) => new Factory_State());
                    }
                    if (St_Prss_Record)
                    {
                        Prss_Record.AddOrUpdate(Step, new Factory_Record(), (key, oldValue) => new Factory_Record());
                    }
                    if (St_Prss_Value)
                    {
                        Prss_Value.AddOrUpdate(Step, new Factory_Value(), (key, oldValue) => new Factory_Value());
                    }
                    return (null, null, null, Step);
                }
                else
                {
                    if (St_Prss_Record && Prss_Record.TryGetValue(Step, out Factory_Record? G_Prss_Record))
                    {
                        _Prss_Record = G_Prss_Record;
                    }
                    if (St_Prss_Value && Prss_Value.TryGetValue(Step, out Factory_Value? G_Prss_Value))
                    {
                        _Prss_Value = G_Prss_Value;
                    }
                    if (St_Prss_State && Prss_State.TryGetValue(Step, out Factory_State? G_Prss_State))
                    {
                        _Prss_State = G_Prss_State;
                    }
                }
                return (_Prss_Record, _Prss_Value, _Prss_State, Step);
            }
            return null;
        }

        private bool ExecuteCommand()
        {
            var Factory = FactoryWork(false, FactoryType.State);

            if (Factory is not null && Factory.Value.Item3 is not null)
            {
                Factory_State _Prss_State = Factory.Value.Item3;
                Logger.Print(RuntimeLog.LogType.Error, "----", Prss_LongTerm.Lt_CurrentApplyCommand);
                if (_Prss_State.St_IsBluetoothBoard)
                {
                    return ProductBlueCache.Write(Prss_LongTerm.Lt_CurrentApplyCommand.Trim());
                }
                else
                {
                    return Server_Power.Execute(Prss_LongTerm.Lt_CurrentApplyCommand.Trim());
                }
            }
            return false;
        }

        private void DoTestFail()
        {
            var Factory = FactoryWork(false, FactoryType.Record);

            if (Factory is not null && 
                Factory.Value.Item1 is not null)
            {
                Factory_Record _Prss_Record = Factory.Value.Item1;

                string Step = Factory.Value.Item4;

                var Differents = _Prss_Record.Rc_CanCheckFields.Select(i => i.Name).ToList().Except(_Prss_Record.Rc_CollectedFields);

                Prss_LongTerm.Lt_ExecptionAtrribute = GetExecptionAttribute(Differents);

                MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Message | MessageProPlantType.Failed,
                                   $"测试步骤: {Step}  测试结果: 不通过  不通过的属性: {Prss_LongTerm.Lt_ExecptionAtrribute}", WorkIndex));
            }
        }

        private void DoPossibleCauseType()
        {
            var Factory = FactoryWork(false, FactoryType.Record);

            if (Factory is not null &&
                Factory.Value.Item1 is not null)
            {
                Factory_Record _Prss_Record = Factory.Value.Item1;

                Application.Current.Dispatcher.InvokeAsync(() =>
                {
                    try
                    {
                        for (int index = 0; index < _Prss_Record.Rc_FailInWhy.Count; index++)
                        {
                            string FailWhy = _Prss_Record.Rc_FailInWhy.GetSafetyChar(index);

                            (FailWhyinDisposeType, object?) FailWhyType = (FailWhyinDisposeType.Invalid, null);
                            if (_Prss_Record.Rc_FailInWhyType.Count > index)
                            {
                                FailWhyType = _Prss_Record.Rc_FailInWhyType.ElementAt(index);
                            }

                            //  执行可能原因辅助措施
                            if (FailWhyType.Item1 == FailWhyinDisposeType.RegexpTool)
                            {
                                string SerialExistsString = _Prss_Record.Rc_SerialPortoutPut.Join("");

                                MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Message,
                                new EnjoyRichTextBox.Text
                                {
                                    TxType = EnjoyRichTextBox.TextType.HyperLink,
                                    Contnet = FailWhy,
                                    FontSize = 19,
                                    Foreground = "CoralRed",
                                    BindingData = new HyperlinkBack
                                    {
                                        LinkType = HyperlinkBackType.OpenRegexpTool,
                                        BindingData = new RegexpTestTool.InfoPakage
                                        {
                                            content = SerialExistsString,
                                            regexp = FailWhyType.Item2?.GetSafetyChar() ?? string.Empty
                                        }
                                    }
                                }));
                            }
                            else if (FailWhyType.Item1 == FailWhyinDisposeType.ContentPopup)
                            {
                                MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Message,
                                new EnjoyRichTextBox.Text
                                {
                                    TxType = EnjoyRichTextBox.TextType.HyperLink,
                                    Contnet = FailWhy,
                                    FontSize = 19,
                                    Foreground = "Lavender",
                                    BindingData = new HyperlinkBack
                                    {
                                        LinkType = HyperlinkBackType.VisibleContentPopup,
                                        BindingData = new EnjoyContentPopue.InfoPakage
                                        {
                                            Contents = FailWhyType.Item2 is null ? [.. _Prss_Record.Rc_SerialPortoutPut] : [FailWhyType.Item2],
                                            Win_Width = 560,
                                            Win_Height = 170
                                        }
                                    }
                                }));
                            }
                            else if (FailWhyType.Item1 == FailWhyinDisposeType.BitwiseTool)
                            {
                                MessagePro?.Invoke(new FlyingDove(MessageProPlantType.Message,
                                new EnjoyRichTextBox.Text
                                {
                                    TxType = EnjoyRichTextBox.TextType.HyperLink,
                                    Contnet = FailWhy,
                                    FontSize = 19,
                                    Foreground = "Lavender",
                                    BindingData = new HyperlinkBack
                                    {
                                        LinkType = HyperlinkBackType.OpenBitwiseTool,
                                        BindingData = FailWhyType.Item2
                                    }
                                }));
                            }
                        }
                        if (_Prss_Record.Rc_FailInWhy.Count == 0)
                        {
                            _Prss_Record.Rc_FailInWhy = [$"当前工序测试未通过，点击该文本检查输出"];

                            _Prss_Record.Rc_FailInWhyType = [(FailWhyinDisposeType.ContentPopup, null)];
                        }
                    } catch (Exception error)
                    {
                        Logger.Print(RuntimeLog.LogType.Fatal, $"message invode error: {error.Message}");
                    }
                });
            }
        }
    }
}
